﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using Newtonsoft.Json;
using System.IO;

using BasePlatformCommon;
using BasePlatformNet;
using BasePlatformCom;
using L9SubSet.lwf;

namespace L9SubSet
{
	public partial class Form_DetectDetail : Form
	{
		private Form_MainSet parentForm = null;

		private BaseCoreNet baseCoreNet = null;
		private BaseCoreCom baseCoreCom = null;
		private ActivePath activePath = ActivePath.None;
        private DetectType detectType = DetectType.Normal;

		private bool lampLoopCheckProcessing = false;

		private LampCheckMethod checkMethod = LampCheckMethod.CheckState;
		private LampCheckMode checkMode = LampCheckMode.RealTime;

		private List<SubTubeData> referSubTubeDataList = null;

		private List<LampStatePara> referResultLampList = null;

		private int totalSubNum = 0;
		private int totalPortNum = 8;

		private int mainIndexPara = -1;
		private int subIndexPara = -1;
		private int portIndexPara = -1;

		private int checkLoopNum = 0;
		private int checkLoopPeriod = 1000;

		private bool runningFlag = false;
		private bool pauseFlag = false;

		// 分控解码器控制权使能状态集合
		private bool[] subControlOpenFlag = null;

		// 委托定义与声明
		public delegate void FillSuccessLampDelagate(int currentSubIndex, int currentPortIndex, LampStatePara statePara, int loopNum, int currentTotalLampNum, int currentRowIndex);
		public FillSuccessLampDelagate fillSuccessLampDelagate;
		public delegate void FillFailLampUpDelegate(int currentSubIndex, int currentPortIndex, LampStatePara refLampStatePara, int loopNum, int currentRowIndex, int failNum);
		public FillFailLampUpDelegate fillFailLampUpDelegate;
		public delegate void FillFailLampDownGridViewDelegate(int checkSubIndex, int checkPortIndex, int currentRowIndex, int loopNum);
		public FillFailLampDownGridViewDelegate fillFailLampDownGridViewDelegate;
		public delegate void FillDeclareLampLineDelegate(int subIndex, int portIndex);
		public FillDeclareLampLineDelegate fillDeclareLampLineDelegate;
		public delegate void ClearValuesDelegate(int rowIndex);
		public ClearValuesDelegate clearValuesDelegate;
		public delegate void ClearDetectDetailGridViewDelegate();
		public ClearDetectDetailGridViewDelegate clearDetectDetailGridViewDelegate;
		public delegate void UpdateCurrentLampLabelDelegate(int checkSubIndex, int checkPortIndex, int currentRowIndex);
		public UpdateCurrentLampLabelDelegate updateCurrentLampLabelDelegate;
		public delegate void RefreshCurrentLampDelegate(int currentSubIndex, int currentPortIndex, LampStatePara lampStatePara, int loopNum, int currentRowIndex, int effectLampNum);
		public RefreshCurrentLampDelegate refreshCurrentLampDelegate;
		public delegate void EnableStartButtonDelegate();
		public EnableStartButtonDelegate enableStartButtonDelegate;
		public delegate void FillReferResultLampLineDelegate();
		public FillReferResultLampLineDelegate fillReferResultLampLineDelegate;
		public delegate void FillReferResultLampLineQuickDelegate();
		public FillReferResultLampLineQuickDelegate fillReferResultLampLineQuickDelegate;

		// 相关颜色
		private ConsoleColor c = Console.ForegroundColor;
		private Color highLightColor = Color.YellowGreen;
		private Color disableColor = Color.Red;

		private int rowHeight = 16;						// 默认行高
		
		private int lastHighLightRowIndex = 0;			// 上次显示的高亮行
		
		private int skipRowNum = 0;						// 跳过行个数, 用于向下填充检测失败的行

		private bool quickRestartFlag = false;			// 快速重启标记

		private bool needRestart = false;				// 需要重启标记

		private bool subIndexComboBoxAction = true;		// subIndexComboBox响应事件使能

		private int lastCheckModeIndex = 0;				// 上次选择的检测模式

		private int currentCheckThreadNum = 0;			// 当前启动的检测线程数

		private bool initDone = false;					// 初始化完成标记

		private bool withSetControlState = false;		// 灯具检测时是否带有获取/解除解码器控制权的操作

		private string lastPath_CheckAccordingFile = "";

		private string section = "DetectDetail";		// 多语言文件配置节名称

		private string tip = "提示";						// MessageBox 题头

		/****************************************************************************/

		// 构造函数
		public Form_DetectDetail(bool showTestTab)
		{
			InitializeComponent();

			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
			this.Font = new System.Drawing.Font(this.Font.Name, 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel, ((byte)(134)));

			initEnvironment(showTestTab);
		}

		// 初始化运行环境
		private void initEnvironment(bool showTestTab)
		{
			tip = LanguageOper.ReadValue("Common", "tipStr");

			// 委托实例化
			fillSuccessLampDelagate = new FillSuccessLampDelagate(fillSuccessLamp);
			fillFailLampUpDelegate = new FillFailLampUpDelegate(fillFailLampUp);
			fillFailLampDownGridViewDelegate = new FillFailLampDownGridViewDelegate(fillFailLampDown);
			fillDeclareLampLineDelegate = new FillDeclareLampLineDelegate(fillDeclareLampLine);
			clearValuesDelegate = new ClearValuesDelegate(clearValues);
			clearDetectDetailGridViewDelegate = new ClearDetectDetailGridViewDelegate(clearDetectDetailGridView);
			updateCurrentLampLabelDelegate = new UpdateCurrentLampLabelDelegate(updateCurrentLampLabel);
			refreshCurrentLampDelegate = new RefreshCurrentLampDelegate(refreshCurrentLamp);
			enableStartButtonDelegate = new EnableStartButtonDelegate(enableStartButton);
			fillReferResultLampLineDelegate = new FillReferResultLampLineDelegate(fillReferResultLampLine);
			fillReferResultLampLineQuickDelegate = new FillReferResultLampLineQuickDelegate(fillReferResultLampLineQuick);

			// 初始化详细信息表格
			initTables();

            //// 检测方法下拉列表
            //checkMechodComboBox.Items.Add("灯具连接检测");
            //checkMechodComboBox.Items.Add("灯具状态检测");
            //if (checkMethod == LampCheckMethod.CheckLink)
            //{
            //    checkMechodComboBox.SelectedIndex = 0;
            //}
            //else if (checkMethod == LampCheckMethod.CheckState)
            //{
            //    checkMechodComboBox.SelectedIndex = 1;
            //}

			// 检测模式下拉列表
			checkModeComboBox.Items.Add("依据布线文件");
			checkModeComboBox.Items.Add("依据搜索结果");
			checkModeComboBox.Items.Add("实时检测");
			if (checkMode == LampCheckMode.UseLwf)
			{
				checkModeComboBox.SelectedIndex = 0;
			}
			else if (checkMode == LampCheckMode.UseResult)
			{
				checkModeComboBox.SelectedIndex = 1;
			}
			else if (checkMode == LampCheckMode.RealTime)
			{
				checkModeComboBox.SelectedIndex = 2;
				checkAccordingTextBox.Enabled = false;
				checkAccordingSelectButton.Enabled = false;
			}

			lastCheckModeIndex = checkModeComboBox.SelectedIndex;

            pauseButton.Enabled = false;

            checkModeComboBox.Enabled = false;

            //if (showTestTab == true)
            //{
            //    showDebugCheckBox.Visible = true;
            //}
            //else
            //{
            //    showDebugCheckBox.Visible = false;
            //    showDebugCheckBox.Checked = false;
            //}

            //for (var i = 0; i < detectDetailGridView.Columns.Count; i++) {
            //    detectDetailGridView.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            //}
            

			// 设置本地化语言
			if (LanguageOper.available == true)
			{
				setLanguageText();
			}
		}

		// 设置本地化语言
		public void setLanguageText()
		{
            return;
			if (LanguageOper.available == false)
			{
				return;
			}

			LanguageOper.SetCurrentCulture();

			tip = LanguageOper.ReadValue("Common", "tipStr");

			// 界面控件文字
			this.Text = LanguageOper.ReadValue(section, "detectDetail.Text");
			rangeLabel.Text = LanguageOper.ReadValue(section, "rangeLabel.Text");
			subTipLabel.Text = LanguageOper.ReadValue(section, "subTipLabel.Text");
			portTipLabel.Text = LanguageOper.ReadValue(section, "portTipLabel.Text");
			//methodLabel.Text = LanguageOper.ReadValue(section, "methodLabel.Text");
			modeLabel.Text = LanguageOper.ReadValue(section, "modeLabel.Text");
			saveCheckModeCheckBox.Text = LanguageOper.ReadValue(section, "saveCheckModeCheckBox.Text");
			checkAccordingLabel.Text = LanguageOper.ReadValue(section, "checkAccordingLabel.Text");
			checkAccordingSelectButton.Text = LanguageOper.ReadValue(section, "checkAccordingSelectButton.Text");
			saveButton.Text = LanguageOper.ReadValue(section, "saveButton.Text");
			//checkMechodComboBox.Items[0] = LanguageOper.ReadValue(section, "checkMechod.Items.0");
			//checkMechodComboBox.Items[1] = LanguageOper.ReadValue(section, "checkMechod.Items.1");
			checkModeComboBox.Items[0] = LanguageOper.ReadValue(section, "checkMode.Items.0");
			checkModeComboBox.Items[1] = LanguageOper.ReadValue(section, "checkMode.Items.1");
			checkModeComboBox.Items[2] = LanguageOper.ReadValue(section, "checkMode.Items.2");
			currentLampTipLabel.Text = LanguageOper.ReadValue(section, "currentLampTipLabel.Text");
			detectedTipLabel.Text = LanguageOper.ReadValue(section, "detectedTipLabel.Text");
			effectTipLabel.Text = LanguageOper.ReadValue(section, "effectTipLabel.Text");
			showDebugCheckBox.Text = LanguageOper.ReadValue(section, "showDebugCheckBox.Text");
			showCVTPCheckBox.Text = LanguageOper.ReadValue(section, "showCVTPCheckBox.Text");
			showVRCheckBox.Text = LanguageOper.ReadValue(section, "showVRCheckBox.Text");
			pauseButton.Text = LanguageOper.ReadValue(section, "str.5");
			startButton.Text = LanguageOper.ReadValue(section, "str.4");
			okButton.Text = LanguageOper.ReadValue(section, "okButton.Text");
			if (LanguageOper.LocalLanguage != LanguageEnum.EN)
			{
				rangeLabel.Location = new Point(12, 18);
				//methodLabel.Location = new Point(304, 18);
				modeLabel.Location = new Point(485, 18);
				currentLampLabel.Location = new Point(120, 404);
			}
			else
			{
				rangeLabel.Location = new Point(25, 18);
				//methodLabel.Location = new Point(285, 18);
				modeLabel.Location = new Point(475, 18);
				currentLampLabel.Location = new Point(110, 404);
			}

			// 详细信息表列头
			detectDetailGridView.Columns[0].HeaderText = LanguageOper.ReadValue(section, "detectDetail.HeadText.0");
			detectDetailGridView.Columns[1].HeaderText = LanguageOper.ReadValue(section, "detectDetail.HeadText.1");
			detectDetailGridView.Columns[2].HeaderText = LanguageOper.ReadValue(section, "detectDetail.HeadText.2");
			detectDetailGridView.Columns[3].HeaderText = LanguageOper.ReadValue(section, "detectDetail.HeadText.3");
			detectDetailGridView.Columns[4].HeaderText = LanguageOper.ReadValue(section, "detectDetail.HeadText.4");
			detectDetailGridView.Columns[5].HeaderText = LanguageOper.ReadValue(section, "detectDetail.HeadText.5");
			detectDetailGridView.Columns[6].HeaderText = LanguageOper.ReadValue(section, "detectDetail.HeadText.6");
			detectDetailGridView.Columns[7].HeaderText = LanguageOper.ReadValue(section, "detectDetail.HeadText.7");
			detectDetailGridView.Columns[8].HeaderText = LanguageOper.ReadValue(section, "detectDetail.HeadText.8");
			detectDetailGridView.Columns[9].HeaderText = LanguageOper.ReadValue(section, "detectDetail.HeadText.9");
			detectDetailGridView.Columns[10].HeaderText = LanguageOper.ReadValue(section, "detectDetail.HeadText.10");
			detectDetailGridView.Columns[11].HeaderText = LanguageOper.ReadValue(section, "detectDetail.HeadText.11");
			detectDetailGridView.Columns[12].HeaderText = LanguageOper.ReadValue(section, "detectDetail.HeadText.12");
		}

		// 设置父窗体引用
		public void setParentForm(Form_MainSet parentForm)
		{
            this.parentForm = parentForm;
		}

		// 设置底层平台引用
		public void setBaseCoreNet(BaseCoreNet baseCoreNet, BaseCoreCom baseCoreCom, ActivePath activePath)
		{
			this.baseCoreNet = baseCoreNet;
			this.baseCoreCom = baseCoreCom;
			this.activePath = activePath;
            if (baseCoreCom == null && activePath == ActivePath.Com) {
                this.activePath = ActivePath.None;
            }
		}

		// 设置灯具巡检参考依据
		public void setReferSubTubeDataList(List<SubTubeData> referSubTubeDataList)
		{
            this.referSubTubeDataList = referSubTubeDataList;
            checkMode = parentForm.lastLampDetectMode;
            checkModeComboBox.SelectedIndex = (int)checkMode;
            checkModeComboBox_SelectedIndexChanged(null, null);
		}

		// 设置巡检参数
		public void setCheckParameter(int totalSubNum, int mainIndex, int subIndex, int portIndex)
		{
			this.totalSubNum = totalSubNum;
			this.mainIndexPara = mainIndex;
			this.subIndexPara = subIndex;
			this.portIndexPara = portIndex;

			subIndexComboBox.Items.Add("全部");
			for (int i = 1; i <= totalSubNum; i++)
			{
				subIndexComboBox.Items.Add(i.ToString());
			}
			subIndexComboBox.SelectedIndex = subIndex;
			
			portIndexComboBox.Items.Add("全部");
			for (int i = 1; i <= totalPortNum; i++)
			{
				portIndexComboBox.Items.Add(i.ToString());
			}
			portIndexComboBox.SelectedIndex = portIndex;

			if (LanguageOper.available == true)
			{
				subIndexComboBox.Items[0] = LanguageOper.ReadValue(section, "str.0");
				portIndexComboBox.Items[0] = LanguageOper.ReadValue(section, "str.0");
			}

			subControlOpenFlag = new bool[totalSubNum];
		}

        // 设置巡检方式
        public void setDetectType(DetectType type) {
            this.detectType = type;
            if (type == DetectType.Normal) {
                modeLabel.Visible = false;
                checkModeComboBox.Visible = false;
            } else {
                modeLabel.Visible = true;
                checkModeComboBox.Visible = true;
            }
        }

		// 初始化详细信息表格
		private void initTables()
		{
			int initLineNum = detectDetailGridView.Size.Height / rowHeight;
			for (int i = 0; i < initLineNum; i++)
			{
				detectDetailGridView.Rows.Add("", "", "", "", "", "", "", "", "", "", "", "", "");
				detectDetailGridView.Rows[i].Height = rowHeight;
			}
		}

		// 窗体显示后处理
		private void Form_DetectDetail_Shown(object sender, EventArgs e)
		{
			if (baseCoreNet == null/* || baseCoreCom == null*/)
			{
				return;
			}

			// 设置灯具巡检模式
			if (parentForm.saveLampCheckModeChecked == true)
			{
				saveCheckModeCheckBox.Checked = true;

				if (parentForm.lastLampDetectMode == LampCheckMode.UseLwf)
				{
					checkModeComboBox.SelectedIndex = 0;
				}
				else if (parentForm.lastLampDetectMode == LampCheckMode.UseResult)
				{
					checkModeComboBox.SelectedIndex = 1;
					checkAccordingTextBox.Text = parentForm.lastCheckAccordingFilePath;
				}
				else if (parentForm.lastLampDetectMode == LampCheckMode.RealTime)
				{
					checkModeComboBox.SelectedIndex = 2;
				}

				checkModeComboBox_SelectedIndexChanged(null, null);
			}

			initDone = true;

			// 开始灯具巡检
			startButton.PerformClick();
		}

		// 窗体关闭前处理
		private void Form_DetectDetail_FormClosing(object sender, FormClosingEventArgs e)
		{
			pauseFlag = false;

			// 清除灯具巡检标记, 恢复拓扑结构检测
			baseCoreNet.setLampCheckProcessing(false);
			lampLoopCheckProcessing = false;
			quickRestartFlag = true;

			if (activePath == ActivePath.Com)
			{
				baseCoreCom.setLampCheckEnable(false);
			}

			this.DialogResult = System.Windows.Forms.DialogResult.OK;
		}

		// 重新开始灯具巡检
		private void restartLampLoopCheck()
		{
			if (subIndexPara < 0 || subIndexPara > 255)
			{
				return;
			}
			else if (portIndexPara < 0 || portIndexPara > totalPortNum)
			{
				return;
			}

            //if (detectType == DetectType.Normal) {
                // 依据布线文件
                if (checkMode == LampCheckMode.UseLwf) {
                    // 填充布线文件中声明的灯具
                    if (this != null && this.Visible) {
                        this.Invoke(fillDeclareLampLineDelegate, subIndexPara, portIndexPara);
                    } else {
                        return;
                    }

                    // 检查当前要巡检的灯具数量
                    if (detectDetailGridView.Rows.Count == 0 || detectDetailGridView.Rows[0].Cells[0].Value.ToString().Equals("")) {
                        string subIndexStr = subIndexComboBox.Text;
                        string portIndexStr = portIndexComboBox.Text;
                        if (runningFlag == true) {
                            initTables();
                            currentLampLabel.Text = "--";
                            effectLampNumLabel.Text = "0";
                            checkedLampNumLabel.Text = "0";

                            string msg = string.Format("分控 {0} 端口 {1} 在布线文件中未挂载灯具点", subIndexStr, portIndexStr);
                            if (LanguageOper.available == true) {
                                msg = string.Format(LanguageOper.ReadValue(section, "msgStr.0"), subIndexStr, portIndexStr);
                            }

                            MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);

                            runningFlag = false;
                            return;
                        }
                    }

                    lastHighLightRowIndex = 0;
                    pauseFlag = false;
                    quickRestartFlag = false;

                    // 启动新的灯具巡检线程
                    Thread t = new Thread(lampLoopCheckProcess_UseLwf);
                    t.IsBackground = true;
                    t.Start();
                }
                    // 依据检测结果
                else if (checkMode == LampCheckMode.UseResult) {
                    // 检查结果文件是否存在
                    if (!checkAccordingTextBox.Text.Equals("") && !File.Exists(checkAccordingTextBox.Text)) {
                        string msg = string.Format("文件 {0} 不存在", checkAccordingTextBox.Text);
                        if (LanguageOper.available == true) {
                            msg = string.Format(LanguageOper.ReadValue(section, "msgStr.1"), checkAccordingTextBox.Text);
                        }

                        MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);

                        runningFlag = false;

                        return;
                    }

                    // 检查当前要巡检的灯具数量
                    if (detectDetailGridView.Rows.Count == 0 || detectDetailGridView.Rows[0].Cells[0].Value.ToString().Equals("")) {
                        string msg = "当前没有要检测的灯具";
                        if (LanguageOper.available == true) {
                            msg = LanguageOper.ReadValue(section, "msgStr.2");
                        }

                        MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);

                        runningFlag = false;

                        return;
                    }

                    // 灰化当前显示的所有结果行
                    if (this != null && this.Visible) {
                        this.Invoke(fillReferResultLampLineQuickDelegate);
                    } else {
                        return;
                    }

                    lastHighLightRowIndex = 0;
                    pauseFlag = false;
                    quickRestartFlag = false;

                    // 启动新的灯具巡检线程
                    Thread t = new Thread(lampLoopCheckProcess_UseResult);
                    t.IsBackground = true;
                    t.Start();
                }
                    // 实时检测
                else if (checkMode == LampCheckMode.RealTime) {
                    // 清空当前显示的结果行
                    if (this != null && this.Visible) {
                        this.Invoke(clearDetectDetailGridViewDelegate);
                    } else {
                        return;
                    }

                    lastHighLightRowIndex = 0;
                    pauseFlag = false;
                    quickRestartFlag = false;

                    // 启动新的灯具巡检线程
                    if (detectType == DetectType.Normal)
                    {
                        Thread t = new Thread(lampLoopCheckProcess_RealTime);
                        t.IsBackground = true;
                        t.Start();
                    }
                    else
                    {
                        Thread t = new Thread(lampLoopCheckProcess_RealTime_RDM);
                        t.IsBackground = true;
                        t.Start();
                    }

                }
            //} else {
            //    // 清空当前显示的结果行
            //    if (this != null && this.Visible) {
            //        this.Invoke(clearDetectDetailGridViewDelegate);
            //    } else {
            //        return;
            //    }

            //    lastHighLightRowIndex = 0;
            //    pauseFlag = false;
            //    quickRestartFlag = false; 
            //    if (activePath == ActivePath.Net) {
            //        if (baseCoreNet.getActiveDevIndex() >= 0) {
            //            // 设置灯具巡检标记, 灯具巡检期间, 停止拓扑结构检测
            //            baseCoreNet.setLampCheckProcessing(true);
            //        }
            //    }

            //    // 启动新的灯具巡检线程
            //    Thread t = new Thread(lampLoopCheckProcess_ArtRDM);
            //    t.IsBackground = true;
            //    t.Start();
            //}


			if (activePath == ActivePath.Com)
			{
				baseCoreCom.setLampCheckEnable(true);
			}
		}

		// 灯具巡检过程 - 根据布线文件 - 线程方法
		private void lampLoopCheckProcess_UseLwf()
		{
			try
			{
				lampLoopCheckProcessing = true;

				currentCheckThreadNum++;

				checkLoopNum = 0;
				while (true)
				{
					if (lampLoopCheckProcessing == false)
					{
						break;
					}
					else if (activePath == ActivePath.None)
					{
						break;
					}

					// 暂停检查点
					pauseCheckPoint(-1);	

					/************************************** 开始单轮巡检 **************************************/

					checkLoopNum++;

					// 修正逻辑：当系统界面左侧设备树刚刚刷新时，点击 "灯具检测" 按钮，无法检测到灯具
					if (activePath == ActivePath.Net)
					{
						if (baseCoreNet.getActiveDevIndex() >= 0)
						{
							// 设置灯具巡检标记, 灯具巡检期间, 停止拓扑结构检测
							baseCoreNet.setLampCheckProcessing(true);
						}
						else
						{
							Thread.Sleep(100);
							checkLoopNum--;
							continue;
						}
					}

					LampStatePara lampStatePara = null;

					int startSubIndex = -1;
					int endSubIndex = -1;
					int startPortIndex = -1;
					int endPortIndex = -1;

					// 分控全局检测
					if (subIndexPara == 0)
					{
						startSubIndex = 0;
						endSubIndex = referSubTubeDataList.Count;
					}
					// 分控定点检测
					else
					{
						startSubIndex = subIndexPara - 1;
						endSubIndex = subIndexPara;
					}

					int thisLoopCheckLampNum = 0;
					int effectLampNum = 0;
					for (int i_sub = startSubIndex; i_sub < endSubIndex; i_sub++)
					{
						if (quickRestartFlag == true)
						{
							break;	// 快速重启检测过程
						}

						// 端口全局检测
						if (portIndexPara == 0)
						{
							startPortIndex = 0;
							endPortIndex = referSubTubeDataList[i_sub].PortData.Count;
						}
						// 端口定点检测
						else
						{
							startPortIndex = portIndexPara - 1;
							endPortIndex = portIndexPara;
						}

						for (int i_port = startPortIndex; i_port < endPortIndex; i_port++)
						{
							int checkSubIndex = i_sub + 1;
							int checkPortIndex = i_port + 1;

							// 暂停检查点
							pauseCheckPoint(checkSubIndex);

							if (quickRestartFlag == true)
							{
								break;	// 快速重启检测过程
							}

							int totalLampNum = referSubTubeDataList[i_sub].PortData[i_port].TubePoint.Count;
							for (int lampIndex = 1; lampIndex <= totalLampNum; lampIndex++)
							{
								if (withSetControlState)
								{
									// 按需获取当前解码器控制权
									if (subControlOpenFlag[checkSubIndex - 1] == false)
									{
										baseCoreNet.setControlState(checkSubIndex, true, false);
										Thread.Sleep(300);
										subControlOpenFlag[checkSubIndex - 1] = true;
										Console.WriteLine(String.Format("SubControl {0}: Set Control State = true", checkSubIndex));
									}
								}

								/*============================== 实际检测过程 ================================*/
								lampStatePara = checkOneLamp(i_sub + 1, i_port + 1, lampIndex);
								/*==========================================================================*/

								// 当前灯具首次未检测到, 重复检测 2 次
								if (lampStatePara == null)
								{
									if (this != null && this.Visible)
									{
										// 更新前台界面 - 添加新行或刷新已有行
										this.BeginInvoke(refreshCurrentLampDelegate, checkSubIndex, checkPortIndex, lampStatePara, checkLoopNum, thisLoopCheckLampNum, effectLampNum);
									}
									else
									{
										return;
									}

									for (int tryNum = 0; tryNum < 2; tryNum++)
									{
										if (quickRestartFlag == true)
										{
											break;	// 快速重启检测过程
										}

										// 暂停检查点
										pauseCheckPoint(checkSubIndex);

										lampStatePara = checkOneLamp(checkSubIndex, checkPortIndex, lampIndex);
										if (lampStatePara != null)
										{
											break;
										}
									}
								}

								if (quickRestartFlag == true)
								{
									break;	// 快速重启检测过程
								}

								// 暂停检查点
								pauseCheckPoint(checkSubIndex);

								// 最终未检测到当前灯具
								if (lampStatePara == null)
								{
									//Console.WriteLine("Check Sub {0} Port {1} Lamp {2}, Fail", checkSubIndex, checkPortIndex, lampIndex);
								}
								// 检测到当前灯具
								else
								{
									effectLampNum++;
									//Console.WriteLine("Check Sub {0} Port {1} Lamp {2}, Success", checkSubIndex, checkPortIndex, lampIndex);
								}

								if (this != null && this.Visible)
								{
									// 更新前台界面 - 添加新行或刷新已有行
									this.BeginInvoke(refreshCurrentLampDelegate, checkSubIndex, checkPortIndex, lampStatePara, checkLoopNum, thisLoopCheckLampNum, effectLampNum);
								}
								else
								{
									return;
								}

								thisLoopCheckLampNum++;
							}
						}
					}

					/************************************** 单轮巡检结束 **************************************/

					// 响应快速重启
					if (quickRestartFlag == true)
					{
						if (this != null && this.Visible && runningFlag == true)
						{
							this.Invoke(clearDetectDetailGridViewDelegate);
							this.Invoke(fillDeclareLampLineDelegate, subIndexPara, portIndexPara);
						}

						c = Console.ForegroundColor;
						Console.ForegroundColor = ConsoleColor.DarkYellow;
						Console.WriteLine("Check loop {0} is interrupted by quickRestartFlag", checkLoopNum);
						Console.ForegroundColor = c;

						lastHighLightRowIndex = 0;
						checkLoopNum = 0;
						quickRestartFlag = false;

						continue;
					}

					// 输出日志
					c = Console.ForegroundColor;
					Console.ForegroundColor = ConsoleColor.DarkYellow;
					Console.WriteLine("Check loop {0} done, Checked Lamp Count = {1}", checkLoopNum, thisLoopCheckLampNum);
					Console.ForegroundColor = c;

					// 本轮未检测到灯具
					if (thisLoopCheckLampNum == 0)
					{
						Thread.Sleep(checkLoopPeriod);
						continue;
					}
				}

				// 解除全部解码器的控制权
				releaseAllSubController();

				// 此巡检线程即将结束
				c = Console.ForegroundColor;
				Console.ForegroundColor = ConsoleColor.Green;
				Console.WriteLine("Current Check Thread Exited");
				Console.ForegroundColor = c;

				if (activePath == ActivePath.Com)
				{
					baseCoreCom.setLampCheckEnable(false);
				}
			}
			catch (Exception ex)
			{
				if (ex.Source.ToString().ToLower().Equals("system.windows.forms"))
				{
					//MessageBoxEx.Show(this, ex.Message + ex.StackTrace + ex.TargetSite, tip, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
				else
				{
					MessageBoxEx.Show(this, ex.Message + ex.StackTrace, tip, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
			}
			finally
			{
				if (this != null && this.Visible)
				{
					this.BeginInvoke(enableStartButtonDelegate);
				}

				lampLoopCheckProcessing = false;
				currentCheckThreadNum--;
			
				// 更改检测模式后, 重新开始灯具巡检
				if (needRestart == true)
				{
					needRestart = false;
					restartLampLoopCheck();
				}
			}
		}

		// 灯具巡检过程 - 根据检测结果 - 线程方法
		private void lampLoopCheckProcess_UseResult()
		{
			try
			{
				lampLoopCheckProcessing = true;

				currentCheckThreadNum++;

				checkLoopNum = 0;
				List<LampStatePara> lampStateParaList = referResultLampList;
				while (true)
				{
					if (lampLoopCheckProcessing == false)
					{
						break;
					}
					else if (activePath == ActivePath.None)
					{
						break;
					}

					// 暂停检查点
					pauseCheckPoint(-1);

					/************************************** 开始单轮巡检 **************************************/

					int thisLoopCheckLampNum = 0;
					int effectLampNum = 0;

					checkLoopNum++;

					// 修正逻辑：当系统界面左侧设备树刚刚刷新时，点击 "灯具检测" 按钮，无法检测到灯具
					if (activePath == ActivePath.Net)
					{
						if (baseCoreNet.getActiveDevIndex() >= 0)
						{
							// 设置灯具巡检标记, 灯具巡检期间, 停止拓扑结构检测
							baseCoreNet.setLampCheckProcessing(true);
						}
						else
						{
							Thread.Sleep(100);
							checkLoopNum--;
							continue;
						}
					}

					int totalCheckNum = lampStateParaList.Count;
					for (int checkIndex = 0; checkIndex < totalCheckNum; checkIndex++)
					{
						LampStatePara referLamp = lampStateParaList[checkIndex];
						int checkSubIndex = referLamp.SubIndex;
						int checkPortIndex = referLamp.PortIndex;
						int checkLampIndex = referLamp.LampIndex;

						if (withSetControlState)
						{
							// 按需获取当前解码器控制权
							if (subControlOpenFlag[checkSubIndex - 1] == false)
							{
								baseCoreNet.setControlState(checkSubIndex, true, false);
								Thread.Sleep(300);
								subControlOpenFlag[checkSubIndex - 1] = true;
								Console.WriteLine(String.Format("SubControl {0}: Set Control State = true", checkSubIndex));
							}
						}

						/*============================== 实际检测过程 ================================*/
						LampStatePara lampStatePara = checkOneLamp(checkSubIndex, checkPortIndex, checkLampIndex);
						/*==========================================================================*/

						// 当前灯具首次未检测到, 重复检测 2 次
						if (lampStatePara == null)
						{
							if (this != null && this.Visible)
							{
								// 更新前台界面 - 添加新行或刷新已有行
								this.BeginInvoke(refreshCurrentLampDelegate, checkSubIndex, checkPortIndex, lampStatePara, checkLoopNum, thisLoopCheckLampNum, effectLampNum);
							}
							else
							{
								return;
							}

							for (int tryNum = 0; tryNum < 2; tryNum++)
							{
								if (quickRestartFlag == true)
								{
									break;	// 快速重启检测过程
								}

								// 暂停检查点
								pauseCheckPoint(checkSubIndex);

								lampStatePara = checkOneLamp(checkSubIndex, checkPortIndex, checkLampIndex);
								if (lampStatePara != null)
								{
									break;
								}
							}
						}

						if (quickRestartFlag == true)
						{
							break;	// 快速重启检测过程
						}

						// 暂停检查点
						pauseCheckPoint(checkSubIndex);

						// 最终未检测到当前灯具
						if (lampStatePara == null)
						{
							//Console.WriteLine("Check Sub {0} Port {1} Lamp {2}, Fail", checkSubIndex, checkPortIndex, lampIndex);
						}
						// 检测到当前灯具
						else
						{
							effectLampNum++;
							//Console.WriteLine("Check Sub {0} Port {1} Lamp {2}, Success", checkSubIndex, checkPortIndex, lampIndex);
						}

						if (this != null && this.Visible)
						{
							// 更新前台界面 - 添加新行或刷新已有行
							this.BeginInvoke(refreshCurrentLampDelegate, checkSubIndex, checkPortIndex, lampStatePara, checkLoopNum, thisLoopCheckLampNum, effectLampNum);
						}
						else
						{
							return;
						}

						thisLoopCheckLampNum++;
					}

					/************************************** 单轮巡检结束 **************************************/

					// 响应快速重启
					if (quickRestartFlag == true)
					{
						if (this != null && this.Visible && runningFlag == true)
						{
							//this.Invoke(clearDetectDetailGridViewDelegate);
						}

						c = Console.ForegroundColor;
						Console.ForegroundColor = ConsoleColor.DarkYellow;
						Console.WriteLine("Check loop {0} is interrupted by quickRestartFlag", checkLoopNum);
						Console.ForegroundColor = c;

						lastHighLightRowIndex = 0;
						checkLoopNum = 0;
						quickRestartFlag = false;

						continue;
					}

					// 输出日志
					c = Console.ForegroundColor;
					Console.ForegroundColor = ConsoleColor.DarkYellow;
					Console.WriteLine("Check loop {0} done, Checked Lamp Count = {1}", checkLoopNum, lampStateParaList.Count);
					Console.ForegroundColor = c;

					// 本轮未检测到灯具
					if (lampStateParaList.Count == 0)
					{
						Thread.Sleep(checkLoopPeriod);
						continue;
					}
				}

				// 解除全部解码器的控制权
				releaseAllSubController();

				// 此巡检线程即将结束
				c = Console.ForegroundColor;
				Console.ForegroundColor = ConsoleColor.Green;
				Console.WriteLine("Current Check Thread Exited");
				Console.ForegroundColor = c;

				if (activePath == ActivePath.Com)
				{
					baseCoreCom.setLampCheckEnable(false);
				}
			}
			catch (Exception ex)
			{
				if (ex.Source.ToString().ToLower().Equals("system.windows.forms"))
				{
					//MessageBoxEx.Show(this, ex.Message + ex.StackTrace + ex.TargetSite, tip, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
				else
				{
					MessageBoxEx.Show(this, ex.Message + ex.StackTrace, tip, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
			}
			finally
			{
				if (this != null && this.Visible)
				{
					this.BeginInvoke(enableStartButtonDelegate);
				}

				lampLoopCheckProcessing = false;
				
				currentCheckThreadNum--;
				
				// 更改检测模式后, 重新开始灯具巡检
				if (needRestart == true)
				{
					needRestart = false;
					restartLampLoopCheck();
				}
			}
		}

		// 灯具巡检过程 - 实时巡检 - 线程方法
        private void lampLoopCheckProcess_RealTime()
        {
            try
            {
                lampLoopCheckProcessing = true;

                currentCheckThreadNum++;

                checkLoopNum = 0;
                List<LampStatePara> lampStateParaList = new List<LampStatePara>();
                while (true)
                {
                    if (lampLoopCheckProcessing == false)
                    {
                        break;
                    }
                    else if (activePath == ActivePath.None)
                    {
                        break;
                    }

                    // 暂停检查点
                    pauseCheckPoint(-1);

                    /************************************** 开始单轮巡检 **************************************/

                    checkLoopNum++;

                    // 修正逻辑：当系统界面左侧设备树刚刚刷新时，点击 "灯具检测" 按钮，无法检测到灯具
                    if (activePath == ActivePath.Net)
                    {
                        if (baseCoreNet.getActiveDevIndex() >= 0)
                        {
                            // 设置灯具巡检标记, 灯具巡检期间, 停止拓扑结构检测
                            baseCoreNet.setLampCheckProcessing(true);
                        }
                        else
                        {
                            Thread.Sleep(100);
                            checkLoopNum--;
                            continue;
                        }
                    }

                    int failNum = 0;
                    int checkLampIndex = 0;
                    LampStatePara lampStatePara = null;
                    lampStateParaList.Clear();

                    int startSubIndex = subIndexPara;
                    int endSubIndex = subIndexPara;
                    if (subIndexPara == 0)
                    {
                        startSubIndex = 1;
                        endSubIndex = totalSubNum;
                    }

                    int currentRowIndex = -1;

                    // 多分控巡检
                    for (int checkSubIndex = startSubIndex; checkSubIndex <= endSubIndex; checkSubIndex++)
                    {
                        int startPortIndex = portIndexPara;
                        int endPortIndex = portIndexPara;
                        if (portIndexPara == 0)
                        {
                            startPortIndex = 1;
                            endPortIndex = totalPortNum;
                        }

                        // 多端口巡检
                        for (int checkPortIndex = startPortIndex; checkPortIndex <= endPortIndex; checkPortIndex++)
                        {
                            checkLampIndex = 0;
                            failNum = 0;

                            // 单端口巡检
                            while (true)
                            {
                                Thread.Sleep(100);
                                if (lampLoopCheckProcessing == false)
                                {
                                    break;
                                }

                                // 暂停检查点
                                pauseCheckPoint(checkSubIndex);

                                if (quickRestartFlag == true)
                                {
                                    break;	// 快速重启检测过程
                                }

                                if (withSetControlState)
                                {
                                    // 按需获取当前解码器控制权
                                    if (subControlOpenFlag[checkSubIndex - 1] == false)
                                    {
                                        baseCoreNet.setControlState(checkSubIndex, true, false);
                                        Thread.Sleep(300);
                                        subControlOpenFlag[checkSubIndex - 1] = true;
                                        Console.WriteLine(String.Format("SubControl {0}: Set Control State = true", checkSubIndex));
                                    }
                                }

                                currentRowIndex++;
                                checkLampIndex++;

                                /*============================== 实际检测过程 ================================*/
                                lampStatePara = checkOneLamp(checkSubIndex, checkPortIndex, checkLampIndex);
                                /*==========================================================================*/

                                // 未检测到当前灯具
                                if (lampStatePara == null)
                                {
                                    failNum++;
                                    if (failNum == 3)
                                    {
                                        // 连续3个灯具未检测到, 结束本轮检查
                                        failNum = 0;	// 错误计数器归零
                                        currentRowIndex -= 3;
                                        break;
                                    }
                                }
                                // 检测到当前灯具
                                else
                                {
                                    lampStateParaList.Add(lampStatePara);

                                    if (failNum > 0)
                                    {
                                        if (this != null && this.Visible)
                                        {
                                            // 更新前台界面 - 向上填充检测失败的行
                                            this.Invoke(fillFailLampUpDelegate, checkSubIndex, checkPortIndex, lampStatePara, checkLoopNum, currentRowIndex, failNum);
                                        }
                                        else
                                        {
                                            return;
                                        }
                                        failNum = 0;	// 错误计数器归零
                                    }

                                    if (this != null && this.Visible)
                                    {
                                        // 更新前台界面 - 添加新行或刷新已有行
                                        this.Invoke(fillSuccessLampDelagate, checkSubIndex, checkPortIndex, lampStatePara, checkLoopNum, lampStateParaList.Count, currentRowIndex);
                                    }
                                    else
                                    {
                                        return;
                                    }
                                }
                            }

                            if (quickRestartFlag == true)
                            {
                                break;	// 快速重启检测过程
                            }

                            // 单端口巡检结束
                            if (this != null && this.Visible)
                            {
                                // 更新前台界面 - 向下填充检测失败的行
                                skipRowNum = 0;
                                this.Invoke(fillFailLampDownGridViewDelegate, checkSubIndex, checkPortIndex, currentRowIndex, checkLoopNum);
                                currentRowIndex += skipRowNum;
                            }
                            else
                            {
                                return;
                            }
                        }

                        if (quickRestartFlag == true)
                        {
                            break;	// 快速重启检测过程
                        }

                        if (withSetControlState)
                        {
                            if (subControlOpenFlag[checkSubIndex - 1] == true)
                            {
                                // 解除当前解码器控制权
                                baseCoreNet.setControlState(checkSubIndex, false, false);
                                Thread.Sleep(300);
                                subControlOpenFlag[checkSubIndex - 1] = false;
                                Console.WriteLine(String.Format("SubControl {0}: Set Control State = false", checkSubIndex));
                            }
                        }
                    }

                    /************************************** 单轮巡检结束 **************************************/

                    // 响应快速重启
                    if (quickRestartFlag == true)
                    {
                        if (this != null && this.Visible && runningFlag == true)
                        {
                            this.Invoke(clearDetectDetailGridViewDelegate);
                        }

                        c = Console.ForegroundColor;
                        Console.ForegroundColor = ConsoleColor.DarkYellow;
                        Console.WriteLine("Check loop {0} is interrupted by quickRestartFlag", checkLoopNum);
                        Console.ForegroundColor = c;

                        lastHighLightRowIndex = 0;
                        checkLoopNum = 0;
                        quickRestartFlag = false;

                        continue;
                    }

                    // 输出日志
                    c = Console.ForegroundColor;
                    Console.ForegroundColor = ConsoleColor.DarkYellow;
                    Console.WriteLine("Check loop {0} done, Checked Lamp Count = {1}", checkLoopNum, lampStateParaList.Count);
                    Console.ForegroundColor = c;

                    // 本轮未检测到灯具
                    if (lampStateParaList.Count == 0)
                    {
                        Thread.Sleep(checkLoopPeriod);
                        continue;
                    }
                }

                // 解除全部解码器的控制权
                releaseAllSubController();

                // 此巡检线程即将结束
                c = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Current Check Thread Exited");
                Console.ForegroundColor = c;

                if (activePath == ActivePath.Com)
                {
                    baseCoreCom.setLampCheckEnable(false);
                }
            }
            catch (Exception ex)
            {
                if (ex.Source.ToString().ToLower().Equals("system.windows.forms"))
                {
                    //MessageBoxEx.Show(this, ex.Message + ex.StackTrace + ex.TargetSite, tip, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    MessageBoxEx.Show(this, ex.Message + ex.StackTrace, tip, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            finally
            {
                if (this != null && this.Visible)
                {
                    this.BeginInvoke(enableStartButtonDelegate);
                }

                lampLoopCheckProcessing = false;

                currentCheckThreadNum--;

                // 更改检测模式后, 重新开始灯具巡检
                if (needRestart == true)
                {
                    needRestart = false;
                    restartLampLoopCheck();
                }
            }
        }

        //RDM巡检
        private void lampLoopCheckProcess_RealTime_RDM()
        {
            try
            {
                lampLoopCheckProcessing = true;

                currentCheckThreadNum++;

                checkLoopNum = 0;
                List<LampStatePara> lampStateParaList = new List<LampStatePara>();
                while (true)
                {
                    if (lampLoopCheckProcessing == false)
                    {
                        break;
                    }
                    else if (activePath == ActivePath.None)
                    {
                        break;
                    }

                    // 暂停检查点
                    pauseCheckPoint(-1);

                    /************************************** 开始单轮巡检 **************************************/

                    checkLoopNum++;

                    // 修正逻辑：当系统界面左侧设备树刚刚刷新时，点击 "灯具检测" 按钮，无法检测到灯具
                    if (activePath == ActivePath.Net)
                    {
                        if (baseCoreNet.getActiveDevIndex() >= 0)
                        {
                            // 设置灯具巡检标记, 灯具巡检期间, 停止拓扑结构检测
                            baseCoreNet.setLampCheckProcessing(true);
                        }
                        else
                        {
                            Thread.Sleep(100);
                            checkLoopNum--;
                            continue;
                        }
                    }
                    if (this != null && this.Visible) {
                        this.Invoke(new Action(() => {
                            if (baseCoreNet.ArtDevList_uu != null) {
                                var list = baseCoreNet.ArtDevList_uu;
                                var totalLamp = 0;
                                for (var i = 0; i < list.Length; i++) {
                                    var info = list[i];
                                    if (info != null) {
                                        if (info.UIDList != null) {
                                            totalLamp += info.UIDList.Length;
                                        }
                                    }
                                }
                                currentLampLabel.Text = totalLamp.ToString();
                            }
                        }));
                    }

                    int failNum = 0;
                    int checkLampIndex = 0;
                    LampStatePara lampStatePara = null;
                    lampStateParaList.Clear();

                    int startSubIndex = subIndexPara;
                    int endSubIndex = subIndexPara;
                    if (subIndexPara == 0)
                    {
                        startSubIndex = 1;
                        endSubIndex = totalSubNum;
                    }

                    int currentRowIndex = -1;

                    // 多分控巡检
                    for (int checkSubIndex = startSubIndex; checkSubIndex <= endSubIndex; checkSubIndex++)
                    {
                        int startPortIndex = portIndexPara;
                        int endPortIndex = portIndexPara;
                        if (portIndexPara == 0)
                        {
                            startPortIndex = 1;
                            endPortIndex = totalPortNum;
                        }

                        // 多端口巡检
                        for (int checkPortIndex = startPortIndex; checkPortIndex <= endPortIndex; checkPortIndex++)
                        {
                            checkLampIndex = 0;
                            failNum = 0;

                            int universe_now = (checkSubIndex - 1) * 8 + checkPortIndex - 1;
                            ArtPortInfo info = baseCoreNet.ArtDevList_uu[universe_now];
                            if (info.UIDList != null)
                            {
                                int lamp_max = info.UIDList.Count();
                                for (int lamp_index = 0; lamp_index < lamp_max; lamp_index++)
                                {
                                    Thread.Sleep(100);
                                    if (lampLoopCheckProcessing == false)
                                    {
                                        break;
                                    }

                                    // 暂停检查点
                                    pauseCheckPoint(checkSubIndex);
                                    if (quickRestartFlag == true)
                                    {
                                        break;	// 快速重启检测过程
                                    }


                                    //检测灯具
                                    //string logMessage = String.Format("Read, universe: {0}, index: {1}, UID: " + info.UIDList[lamp_index], universe_now, lamp_index);
                                    //Console.WriteLine(logMessage); 
                                    
                                    lampStatePara = baseCoreNet.checkOneLamp_Rdm(universe_now, info.UIDList[lamp_index]);
                                    currentRowIndex++;

                                    if (lampStatePara.detect_ok == true)
                                        lampStateParaList.Add(lampStatePara);

                                    if (this != null && this.Visible)
                                    {
                                        // 更新前台界面 - 添加新行或刷新已有行
                                        this.Invoke(fillSuccessLampDelagate, checkSubIndex, checkPortIndex, lampStatePara, checkLoopNum, lampStateParaList.Count, currentRowIndex);
                                    }
                                }
                            }

                            if (quickRestartFlag == true)
                            {
                                break;	// 快速重启检测过程
                            }

                            // 单端口巡检结束
                            if (this != null && this.Visible)
                            {
                                // 更新前台界面 - 向下填充检测失败的行
                                skipRowNum = 0;
                                this.Invoke(fillFailLampDownGridViewDelegate, checkSubIndex, checkPortIndex, currentRowIndex, checkLoopNum);
                                currentRowIndex += skipRowNum;
                            }
                            else
                            {
                                return;
                            }
                        }

                        if (quickRestartFlag == true)
                        {
                            break;	// 快速重启检测过程
                        }
                    }

                    /************************************** 单轮巡检结束 **************************************/

                    // 响应快速重启
                    if (quickRestartFlag == true)
                    {
                        if (this != null && this.Visible && runningFlag == true)
                        {
                            this.Invoke(clearDetectDetailGridViewDelegate);
                        }

                        c = Console.ForegroundColor;
                        Console.ForegroundColor = ConsoleColor.DarkYellow;
                        Console.WriteLine("Check loop {0} is interrupted by quickRestartFlag", checkLoopNum);
                        Console.ForegroundColor = c;

                        lastHighLightRowIndex = 0;
                        checkLoopNum = 0;
                        quickRestartFlag = false;

                        continue;
                    }

                    // 输出日志
                    c = Console.ForegroundColor;
                    Console.ForegroundColor = ConsoleColor.DarkYellow;
                    Console.WriteLine("Check loop {0} done, Checked Lamp Count = {1}", checkLoopNum, lampStateParaList.Count);
                    Console.ForegroundColor = c;

                    // 本轮未检测到灯具
                    if (lampStateParaList.Count == 0)
                    {
                        Thread.Sleep(checkLoopPeriod);
                        continue;
                    }
                }

                // 解除全部解码器的控制权
                releaseAllSubController();

                // 此巡检线程即将结束
                c = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Current Check Thread Exited");
                Console.ForegroundColor = c;

                if (activePath == ActivePath.Com)
                {
                    baseCoreCom.setLampCheckEnable(false);
                }
            }
            catch (Exception ex)
            {
                if (ex.Source.ToString().ToLower().Equals("system.windows.forms"))
                {
                    //MessageBoxEx.Show(this, ex.Message + ex.StackTrace + ex.TargetSite, tip, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    MessageBoxEx.Show(this, ex.Message + ex.StackTrace, tip, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            finally
            {
                if (this != null && this.Visible)
                {
                    this.BeginInvoke(enableStartButtonDelegate);
                }

                lampLoopCheckProcessing = false;

                currentCheckThreadNum--;

                // 更改检测模式后, 重新开始灯具巡检
                if (needRestart == true)
                {
                    needRestart = false;
                    restartLampLoopCheck();
                }
            }
        }

        // RDM轮询检测
        private void lampLoopCheckProcess_ArtRDM() {
            try {
                lampLoopCheckProcessing = true;

                currentCheckThreadNum++;

                checkLoopNum = 0;
                List<LampStatePara> lampStateParaList = new List<LampStatePara>();
                while (true) {
                    if (lampLoopCheckProcessing == false) {
                        break;
                    } else if (activePath == ActivePath.None) {
                        break;
                    }
                    var currChain = baseCoreNet.GetCurrArtDeviceDetailList();
                    if (currChain == null) {
                        Thread.Sleep(checkLoopPeriod);
                        continue;
                    }
                    var currDic = currChain.DetailList;

                    // 暂停检查点
                    pauseCheckPoint(-1);

                    /************************************** 开始单轮巡检 **************************************/

                    checkLoopNum++;

                    int failNum = 0;
                    LampStatePara lampStatePara = null;
                    lampStateParaList.Clear();

                    int startSubIndex = subIndexPara;
                    int endSubIndex = subIndexPara;
                    if (subIndexPara == 0) {
                        startSubIndex = 1;
                        endSubIndex = totalSubNum;
                    }

                    int currentRowIndex = -1;
                    var errorFlag = false;
                    if (checkMode == LampCheckMode.UseLwf) {
                        if (referSubTubeDataList == null) {
                            errorFlag = true;
                        }
                    } else if (checkMode == LampCheckMode.UseResult) {
                        var baseChain = baseCoreNet.GetBaseArtDevChain();
                        if (baseChain == null) {
                            errorFlag = true;
                        }
                    }
                    // 多分控巡检
                    for (int checkSubIndex = startSubIndex; checkSubIndex <= endSubIndex; checkSubIndex++) {
                        if (!currDic.ContainsKey(checkSubIndex)) {
                            continue;
                        }
                        if (checkMode == LampCheckMode.UseLwf) {
                            if (!errorFlag) {
                                if (referSubTubeDataList.Count >= checkSubIndex) {
                                    errorFlag = true;
                                }
                            }
                        } else if (checkMode == LampCheckMode.UseResult) {
                            if (!errorFlag) {
                                var baseChain = baseCoreNet.GetBaseArtDevChain();
                                var baseDic = baseChain.DetailList;
                                if (baseDic.Count >= checkSubIndex) {
                                    errorFlag = true;
                                }
                            }
                        }
                        var subInfo = currDic[checkSubIndex];
                        int startPortIndex = portIndexPara;
                        int endPortIndex = portIndexPara;
                        if (portIndexPara == 0) {
                            startPortIndex = 1;
                            endPortIndex = subInfo.Count;
                        }
                        // 多端口巡检
                        for (int checkPortIndex = startPortIndex; checkPortIndex <= endPortIndex; checkPortIndex++) {
                            failNum = 0;
                            var portInfo = subInfo[checkPortIndex - 1];
                            var unv = portInfo.Universe;
                            var devList = portInfo.DeviceList;
                            if (checkMode == LampCheckMode.UseLwf) {
                                if (!errorFlag) {
                                    var subData = referSubTubeDataList[checkSubIndex];
                                    if (subData.PortData.Count <= checkPortIndex) {
                                        errorFlag = true;
                                    }
                                }
                            } else if (checkMode == LampCheckMode.UseResult) {
                                if (!errorFlag) {
                                    var baseChain = baseCoreNet.GetBaseArtDevChain();
                                    var baseDic = baseChain.DetailList;
                                    if (!baseDic.ContainsKey(checkSubIndex)) {
                                        errorFlag = true;
                                    } else {
                                        var portList = baseDic[checkSubIndex];
                                        if (portList.Count <= checkPortIndex) {
                                            errorFlag = true;
                                        }
                                    }
                                }
                            }
                            // 单端口巡检
                            for (var checkLampIndex = 0; checkLampIndex < devList.Count; checkLampIndex++) {
                                Thread.Sleep(100);
                                if (lampLoopCheckProcessing == false) {
                                    break;
                                }

                                // 暂停检查点
                                pauseCheckPoint(checkSubIndex);

                                if (quickRestartFlag == true) {
                                    break;	// 快速重启检测过程
                                }
                                
                                currentRowIndex++;
                                var devInfo = devList[checkLampIndex];
                                /*============================== 实际检测过程 ================================*/
                                devInfo = baseCoreNet.ReadArtDevDetail(devInfo.UID, unv, true);
                                if (devInfo != null) {
                                    lampStatePara = new LampStatePara();
                                    lampStatePara.SubIndex = checkSubIndex;
                                    lampStatePara.PortIndex = checkPortIndex;
                                    lampStatePara.LampIndex = checkLampIndex + 1;
                                    lampStatePara.RdmSeg = devInfo.UID;
                                    lampStatePara.Version = devInfo.SoftwareVersionID;
                                    lampStatePara.DmxAddr = devInfo.DMXAddr;
                                    var sensorList = devInfo.SensorList;
                                    if (sensorList != null && sensorList.Count != 0) {
                                        for (var i = 0; i < sensorList.Count;i++ ) {
                                            var sensor = sensorList[i];
                                            var def = sensor.Definition;
                                            var val = sensor.Value;
                                            if (def != null && val != null) {
                                                var type = def.Type;
                                                var value = val.RealCurrVal;
                                                switch (type) {
                                                    case SensorType.Current:
                                                        lampStatePara.Current = (int)(value * 1000);
                                                        break;
                                                    case SensorType.Voltage:
                                                        lampStatePara.Voltage = (int)(value * 100);
                                                        break;
                                                    case SensorType.Temperature:
                                                        lampStatePara.Temperature = (int)(value * 10);
                                                        break;
                                                }
                                            }
                                        }
                                    }
                                }
                                /*==========================================================================*/

                                // 未检测到当前灯具
                                if (lampStatePara == null) {
                                    failNum++;
                                }
                                    // 检测到当前灯具
                                else {
                                    lampStateParaList.Add(lampStatePara);

                                    if (failNum > 0) {
                                        if (this != null && this.Visible) {
                                            // 更新前台界面 - 向上填充检测失败的行
                                            //this.Invoke(fillFailLampUpDelegate, checkSubIndex, checkPortIndex, lampStatePara, checkLoopNum, currentRowIndex, failNum);
                                        } else {
                                            return;
                                        }
                                        failNum = 0;	// 错误计数器归零
                                    }

                                    if (this != null && this.Visible) {
                                        // 更新前台界面 - 添加新行或刷新已有行
                                        this.Invoke(fillSuccessLampDelagate, checkSubIndex, checkPortIndex, lampStatePara, checkLoopNum, lampStateParaList.Count, currentRowIndex);
                                    } else {
                                        return;
                                    }
                                }
                            }

                            if (quickRestartFlag == true) {
                                break;	// 快速重启检测过程
                            } 

                            // 单端口巡检结束
                            if (this != null && this.Visible) {
                                // 更新前台界面 - 向下填充检测失败的行
                                skipRowNum = 0;
                                this.Invoke(fillFailLampDownGridViewDelegate, checkSubIndex, checkPortIndex, currentRowIndex, checkLoopNum);
                                currentRowIndex += skipRowNum;

                                if (checkMode == LampCheckMode.UseLwf) {
                                    if (errorFlag) {
                                        for (var i = 0; i < devList.Count; i++) {
                                            this.Invoke(new Action(() => {
                                                var rowIndex = currentRowIndex - i - skipRowNum;
                                                changeForeColor(rowIndex, Color.Red);
                                            }));
                                        }
                                    } else {
                                        var lwfCnt = referSubTubeDataList[checkSubIndex - 1].PortData[checkPortIndex - 1].TubePoint.Count;
                                        var lampCnt = devList.Count;
                                        if (lwfCnt < lampCnt) {
                                            for (var i = lwfCnt; i < lampCnt; i++) {
                                                this.Invoke(new Action(() => {
                                                    var rowIndex = currentRowIndex - i - skipRowNum;
                                                    changeForeColor(rowIndex, Color.Red);
                                                }));
                                            }
                                        } else if (lwfCnt > lampCnt) {
                                            for (var i = lampCnt; i < lwfCnt; i++) {
                                                this.Invoke(new Action(() => {
                                                    addBlankLine(checkSubIndex, checkPortIndex, i, checkLoopNum, Color.Red, Color.White);
                                                }));
                                            }
                                        }
                                    }
                                } else if (checkMode == LampCheckMode.UseResult) {
                                    if (errorFlag) {
                                        for (var i = 0; i < devList.Count; i++) {
                                            this.Invoke(new Action(() => {
                                                var rowIndex = currentRowIndex - i - skipRowNum;
                                                changeForeColor(rowIndex, Color.Red);
                                            }));
                                        }
                                    } else {
                                        var baseChain = baseCoreNet.GetBaseArtDevChain();
                                        var baseDic = baseChain.DetailList;
                                        var baseCnt = baseDic[checkSubIndex][checkPortIndex - 1].DeviceList.Count;
                                        var lampCnt = devList.Count;
                                        if (baseCnt < lampCnt) {
                                            for (var i = baseCnt; i < lampCnt; i++) {
                                                this.Invoke(new Action(() => {
                                                    var rowIndex = currentRowIndex - i - skipRowNum;
                                                    changeForeColor(rowIndex, Color.Red);
                                                }));
                                            }
                                        } else if (baseCnt > lampCnt) {
                                            for (var i = lampCnt; i < baseCnt; i++) {
                                                this.Invoke(new Action(() => {
                                                    addBlankLine(checkSubIndex, checkPortIndex, i, checkLoopNum, Color.Red, Color.White);
                                                }));
                                            }
                                        }
                                    }
                                }
                            } else {
                                return;
                            }
                        }

                        if (quickRestartFlag == true) {
                            break;	// 快速重启检测过程
                        }
                    }

                    /************************************** 单轮巡检结束 **************************************/

                    // 响应快速重启
                    if (quickRestartFlag == true) {
                        if (this != null && this.Visible && runningFlag == true) {
                            this.Invoke(clearDetectDetailGridViewDelegate);
                        }

                        c = Console.ForegroundColor;
                        Console.ForegroundColor = ConsoleColor.DarkYellow;
                        Console.WriteLine("Check loop {0} is interrupted by quickRestartFlag", checkLoopNum);
                        Console.ForegroundColor = c;

                        lastHighLightRowIndex = 0;
                        checkLoopNum = 0;
                        quickRestartFlag = false;

                        continue;
                    }

                    // 输出日志
                    c = Console.ForegroundColor;
                    Console.ForegroundColor = ConsoleColor.DarkYellow;
                    Console.WriteLine("Check loop {0} done, Checked Lamp Count = {1}", checkLoopNum, lampStateParaList.Count);
                    Console.ForegroundColor = c;

                    // 本轮未检测到灯具
                    if (lampStateParaList.Count == 0) {
                        Thread.Sleep(checkLoopPeriod);
                        continue;
                    }
                }

                // 此巡检线程即将结束
                c = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Current Check Thread Exited");
                Console.ForegroundColor = c;

                if (activePath == ActivePath.Com) {
                    baseCoreCom.setLampCheckEnable(false);
                }
            } catch (Exception ex) {
                if (ex.Source.ToString().ToLower().Equals("system.windows.forms")) {
                    //MessageBoxEx.Show(this, ex.Message + ex.StackTrace + ex.TargetSite, tip, MessageBoxButtons.OK, MessageBoxIcon.Error);
                } else {
                    MessageBoxEx.Show(this, ex.Message + ex.StackTrace, tip, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            } finally {
                if (this != null && this.Visible) {
                    this.BeginInvoke(enableStartButtonDelegate);
                }

                lampLoopCheckProcessing = false;

                currentCheckThreadNum--;

                // 更改检测模式后, 重新开始灯具巡检
                if (needRestart == true) {
                    needRestart = false;
                    restartLampLoopCheck();
                }
            }
        }

		// 暂停检查点
		private void pauseCheckPoint(int currentSubIndex)
		{
			if (pauseFlag == true)
			{
				// 解除全部解码器的控制权
				releaseAllSubController();

				// 循环等待
				while (pauseFlag == true)
				{
					Thread.Sleep(200);
				}

				if (withSetControlState)
				{
					// 退出暂停, 按需获取当前解码器控制权
					if (currentSubIndex > 0 && subControlOpenFlag[currentSubIndex - 1] == false)
					{
						baseCoreNet.setControlState(currentSubIndex, true, false);
						Thread.Sleep(300);
						subControlOpenFlag[currentSubIndex - 1] = true;
						Console.WriteLine(String.Format("SubControl {0}: Set Control State = true", currentSubIndex));
					}
				}
			}
		}

		// 解除全部解码器的控制权
		private void releaseAllSubController()
		{
			if (subControlOpenFlag != null)
			{
				for (int k = 0; k < subControlOpenFlag.Length; k++)
				{
					if (withSetControlState)
					{
						// 解除解码器控制权
						if (subControlOpenFlag[k] == true)
						{
							baseCoreNet.setControlState(k, false, false);
							Thread.Sleep(300);
							subControlOpenFlag[k] = false;
							Console.WriteLine(String.Format("SubControl {0}: Set Control State = false", k + 1));
						}
					}
				}
			}
		}

		// 检测单个灯具
        private LampStatePara checkOneLamp(int checkSubIndex, int checkPortIndex, int checkLampIndex)
        {
            LampStatePara res = null;

            if (activePath == ActivePath.Net)
            {
                res = baseCoreNet.getLampStatePara(checkSubIndex, checkPortIndex, checkLampIndex);
            }
            else if (activePath == ActivePath.Com)
            {
                //Console.WriteLine(string.Format("checkOneLamp, sub = {0}, port = {1}, lamp = {2}", checkSubIndex, checkPortIndex, checkLampIndex));
                res = baseCoreCom.getLampStatePara(checkSubIndex, checkPortIndex, checkLampIndex);
            }

            if (this != null && this.Visible && res != null)
            {
                //this.BeginInvoke(updateCurrentLampLabelDelegate, checkSubIndex, checkPortIndex, checkLampIndex);
            }

            return res;
        }

        // 根据巡检结果更新前台界面 - 检测成功的灯具
		private void fillSuccessLamp(int currentSubIndex, int currentPortIndex, LampStatePara lampStatePara, int loopNum, int currentTotalLampNum, int currentRowIndex)
		{
			if (lampStatePara == null)
			{
				return;
			}

			if (lampLoopCheckProcessing == false)
			{
				return;
			}

			if (currentRowIndex < detectDetailGridView.Rows.Count)
			{
				// 刷新表格中的一行数据
				refreshValues(currentRowIndex, currentSubIndex, currentPortIndex, lampStatePara, loopNum, Color.Black, highLightColor);
			}
			else
			{
				// 向表格添加新一行数据
				addNewLine(currentSubIndex, currentPortIndex, lampStatePara, loopNum, Color.Black, highLightColor);
			}

			// 滚动条跟随
			//try
			//{
			//	detectDetailGridView.FirstDisplayedScrollingRowIndex = currentRowIndex;
			//}
			//catch (Exception ex)
			//{
			//	MessageBoxEx.Show(this, ex.Message + ex.StackTrace, tip, MessageBoxButtons.OK, MessageBoxIcon.Error);
			//}

			effectLampNumLabel.Text = currentTotalLampNum.ToString();
			checkedLampNumLabel.Text = (currentRowIndex+1).ToString();
		}

		// 向上填充检测失败的行
		private void fillFailLampUp(int currentSubIndex, int currentPortIndex, LampStatePara refLampStatePara, int loopNum, int currentRowIndex, int failNum)
		{
			if (lampLoopCheckProcessing == false)
			{
				return;
			}

			for (int i = failNum; i >= 1; i--)
			{
				int rowIndex = currentRowIndex - i;

				if (rowIndex >= detectDetailGridView.Rows.Count)
				{
					detectDetailGridView.Rows.Add();
					detectDetailGridView.Rows[detectDetailGridView.Rows.Count - 1].Height = rowHeight;
				}

				detectDetailGridView.Rows[rowIndex].Cells[0].Value = currentSubIndex;
				detectDetailGridView.Rows[rowIndex].Cells[1].Value = currentPortIndex;
				detectDetailGridView.Rows[rowIndex].Cells[2].Value = refLampStatePara.LampIndex - i;
				detectDetailGridView.Rows[rowIndex].Cells[3].Value = "--";
				detectDetailGridView.Rows[rowIndex].Cells[4].Value = "";
				detectDetailGridView.Rows[rowIndex].Cells[5].Value = "--";
				detectDetailGridView.Rows[rowIndex].Cells[6].Value = "--";
				detectDetailGridView.Rows[rowIndex].Cells[7].Value = "--";
				detectDetailGridView.Rows[rowIndex].Cells[8].Value = "--";
				detectDetailGridView.Rows[rowIndex].Cells[9].Value = "--";
				detectDetailGridView.Rows[rowIndex].Cells[10].Value = "--";
				detectDetailGridView.Rows[rowIndex].Cells[11].Value = "--";
				detectDetailGridView.Rows[rowIndex].Cells[12].Value = loopNum;

				changeForeColor(rowIndex, Color.Red);
				changeBackColor(rowIndex, Color.White);
			}
		}

		// 向下填充检测失败的行（同分控、同端口）
		private void fillFailLampDown(int currentSubIndex, int currentPortIndex, int currentRowIndex, int loopNum)
		{
			if (lampLoopCheckProcessing == false)
			{
				return;
			}

			currentRowIndex++;
			skipRowNum = 0;
			while (true)
			{
                if (currentRowIndex >= detectDetailGridView.Rows.Count)
                {
                    break;
                }

				if (lampLoopCheckProcessing == false)
				{
					return;
				}

				int cSubIndex = -1;
				int cPortIndex = -1;

				int.TryParse(detectDetailGridView.Rows[currentRowIndex].Cells[0].Value.ToString(), out cSubIndex);
				int.TryParse(detectDetailGridView.Rows[currentRowIndex].Cells[1].Value.ToString(), out cPortIndex);

				if (cSubIndex == -1 || cPortIndex == -1)
				{
					break;
				}
				else if (currentSubIndex != cSubIndex || currentPortIndex != cPortIndex)
				{
					break;
				}
				else
				{
					detectDetailGridView.Rows[currentRowIndex].Cells[3].Value = "--";
					detectDetailGridView.Rows[currentRowIndex].Cells[4].Value = "";
					detectDetailGridView.Rows[currentRowIndex].Cells[5].Value = "--";
					detectDetailGridView.Rows[currentRowIndex].Cells[6].Value = "--";
					detectDetailGridView.Rows[currentRowIndex].Cells[7].Value = "--";
					detectDetailGridView.Rows[currentRowIndex].Cells[8].Value = "--";
					detectDetailGridView.Rows[currentRowIndex].Cells[9].Value = "--";
					detectDetailGridView.Rows[currentRowIndex].Cells[10].Value = "--";
					detectDetailGridView.Rows[currentRowIndex].Cells[11].Value = "--";
					detectDetailGridView.Rows[currentRowIndex].Cells[12].Value = loopNum;

					changeForeColor(currentRowIndex, Color.Red);

					currentRowIndex++;
					skipRowNum++;
				}
			}
		}

		// 填充布线文件中声明的灯具 - 【依据布线文件检测】
		private void fillDeclareLampLine(int subIndex, int portIndex)
		{
			detectDetailGridView.Rows.Clear();

			int startSubIndex = -1;
			int endSubIndex = -1;
			int startPortIndex = -1;
			int endPortIndex = -1;

			// 分控全局检测
			if (subIndex == 0)
			{
				startSubIndex = 0;
				endSubIndex = referSubTubeDataList.Count;
			}
			// 分控定点检测
			else
			{
				startSubIndex = subIndex - 1;
				endSubIndex = subIndex;
			}

			List<DataGridViewRow> blankRowList = new List<DataGridViewRow>();
			for (int i_sub = startSubIndex; i_sub < endSubIndex; i_sub++)
			{
				// 端口全局检测
				if (portIndex == 0)
				{
					startPortIndex = 0;
					endPortIndex = referSubTubeDataList[i_sub].PortData.Count;
				}
				// 端口定点检测
				else
				{
					startPortIndex = portIndex - 1;
					endPortIndex = portIndex;
				}

				for (int i_port = startPortIndex; i_port < endPortIndex; i_port++)
				{
					int totalLampNum = referSubTubeDataList[i_sub].PortData[i_port].TubePoint.Count;
					for (int lampIndex = 1; lampIndex <= totalLampNum; lampIndex++)
					{
						//addBlankLine(i_sub + 1, i_port + 1, lampIndex, 0, Color.Black, Color.White);
						DataGridViewRow oneRow = new DataGridViewRow();
						for (int k = 0; k < 13; k++)
						{
							oneRow.Cells.Add(new DataGridViewTextBoxCell());
						}
						oneRow.Cells[0].Value = (i_sub + 1).ToString();
						oneRow.Cells[1].Value = (i_port + 1).ToString();
						oneRow.Cells[2].Value = lampIndex.ToString();
						oneRow.Cells[3].Value = "--";
						oneRow.Cells[4].Value = "";
						oneRow.Cells[5].Value = "--";
						oneRow.Cells[6].Value = "--";
						oneRow.Cells[7].Value = "--";
						oneRow.Cells[8].Value = "--";
						oneRow.Cells[9].Value = "--";
						oneRow.Cells[10].Value = "--";
						oneRow.Cells[11].Value = "--";
						oneRow.Cells[12].Value = "0";

						oneRow.DefaultCellStyle.ForeColor = Color.Gray;
						oneRow.Height = rowHeight;
						blankRowList.Add(oneRow);
					}
				}
			}

			// 批量添加空白行
			detectDetailGridView.Rows.AddRange(blankRowList.ToArray());
		}

		// 刷新当前行 - 【依据布线文件检测】
		private void refreshCurrentLamp(int currentSubIndex, int currentPortIndex, LampStatePara lampStatePara, int loopNum, int currentRowIndex, int effectLampNum)
		{
			if (lampLoopCheckProcessing == false)
			{
				return;
			}

			if (pauseFlag == true)
			{
				return;
			}

			if (lampStatePara == null)
			{
				detectDetailGridView.Rows[currentRowIndex].Cells[10].Value = loopNum;
				changeForeColor(currentRowIndex, Color.Red);
				changeBackColor(currentRowIndex, highLightColor);
			}
			else
			{
				// 刷新表格中的一行数据
				refreshValues(currentRowIndex, currentSubIndex, currentPortIndex, lampStatePara, loopNum, Color.Black, highLightColor);
			}

			checkedLampNumLabel.Text = (currentRowIndex + 1).ToString();
			effectLampNumLabel.Text = effectLampNum.ToString();
		}

		// 填充检测结果中保存的灯具行 - 【依据现有结果检测】
		private void fillReferResultLampLine()
		{
			if (referResultLampList == null)
			{
				return;
			}

			detectDetailGridView.Rows.Clear();

			int currentRowIndex = -1;
			for (int k = 0; k < referResultLampList.Count; k++)
			{
				LampStatePara lampStatePara = referResultLampList[k];
				currentRowIndex++;
				if (lampStatePara.DmxAddr == -1 || lampStatePara.LampId == -1 || lampStatePara.Current == int.MinValue)
				{
					addBlankLine(lampStatePara.SubIndex, lampStatePara.PortIndex, lampStatePara.LampIndex, 0, Color.Gray, Color.White);
				}
				else
				{
					addNewLine(lampStatePara.SubIndex, lampStatePara.PortIndex, lampStatePara, 0, Color.Gray, Color.White);
				}
			}
			
			// 补齐空行
			int initLineNum = detectDetailGridView.Size.Height / rowHeight;
			for (int k = currentRowIndex + 1; k < initLineNum; k++)
			{
				detectDetailGridView.Rows.Add("", "", "", "", "", "", "", "", "", "", "", "", "");
				detectDetailGridView.Rows[k].Height = rowHeight;
			}
		}

		// 灰化检测结果中保存的灯具行（快速） - 【依据现有结果检测】
		private void fillReferResultLampLineQuick()
		{
			int rowCount = detectDetailGridView.Rows.Count;

			for (int i = 0; i < rowCount; i++)
			{
				changeForeColor(i, Color.Gray);
				changeBackColor(i, Color.White);
				if (detectDetailGridView.Rows[i].Cells[12].Value != null && !detectDetailGridView.Rows[i].Cells[12].Value.ToString().Equals(""))
				{
					detectDetailGridView.Rows[i].Cells[12].Value = "0";
				}
			}
		}

		// 向表格中添加空白行
		private void addBlankLine(int currentSubIndex, int currentPortIndex, int currentLampIndex, int loopNum, Color foreColor, Color backColor)
		{
			try
			{
                detectDetailGridView.Rows.Add(currentSubIndex, currentPortIndex, "--", currentLampIndex, "--", "", "--", "--", "--", "--", "--", loopNum, "--");

				int rowIndex = detectDetailGridView.Rows.Count - 1;

				detectDetailGridView.Rows[rowIndex].Height = rowHeight;
				changeForeColor(rowIndex, foreColor);
				changeBackColor(rowIndex, backColor);
			}
			catch (Exception ex)
			{
				MessageBoxEx.Show(this, ex.Message + ex.StackTrace, tip, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		// 向表格中添加有数据的新行
		private void addNewLine(int currentSubIndex, int currentPortIndex, LampStatePara lampStatePara, int loopNum, Color foreColor, Color backColor)
		{
			try
			{
				// 电流、电压、温度
				string current = String.Format("{0:f3}", lampStatePara.Current / 1000.0);
				string voltage = String.Format("{0:f2}", lampStatePara.Voltage / 100.0);
				string temperature = String.Format("{0:f1}", lampStatePara.Temperature / 10.0);

				string unSupport = "不支持";
				string overload = "超量程";
				if (LanguageOper.available == true)
				{
					unSupport = LanguageOper.ReadValue(section, "msgStr.1");
					overload = LanguageOper.ReadValue(section, "msgStr.2");
				}

				if (lampStatePara.Current == 0xffff)
				{
					current = unSupport;
				}
				else if (lampStatePara.Current == 0xfffe)
				{
					current = overload;
				}

				if (lampStatePara.Voltage == 0xffff)
				{
					voltage = unSupport;
				}
				else if (lampStatePara.Voltage == 0xfffe)
				{
					voltage = overload;
				}

				if (lampStatePara.Temperature == 0xffff)
				{
					temperature = unSupport;
				}
				else if (lampStatePara.Temperature == 0xfffe)
				{
					temperature = overload;
				}

				// 功率 - 电流和电压有一项不支持时，功率也不支持
				string power = String.Format("{0:f3}", (lampStatePara.Current / 1000.0) * (lampStatePara.Voltage / 100.0));
				if (lampStatePara.Current == 0xffff || lampStatePara.Voltage == 0xffff)
				{
					power = unSupport;
				}

				string version = "v";

				string rdmId = "r";

                if (!lampStatePara.detect_ok) {
                    detectDetailGridView.Rows.Add(currentSubIndex, currentPortIndex, rdmId, "--", "--", "", "--", "--", "--", "--", "--", loopNum, "--");
                    var index = detectDetailGridView.Rows.Count - 1;
                    changeForeColor(index, Color.Red);
                    changeBackColor(index, backColor);
                    detectDetailGridView.Rows[index].Height = rowHeight;
                    return;
                } else {
                    detectDetailGridView.Rows.Add(currentSubIndex, currentPortIndex, rdmId, lampStatePara.LampIndex, lampStatePara.DmxAddr, lampStatePara.LampChannel, lampStatePara.DebugInfo, temperature, current, voltage, power, loopNum, version);

                }

				int rowIndex = detectDetailGridView.Rows.Count - 1;

				detectDetailGridView.Rows[rowIndex].Height = rowHeight;
				changeForeColor(rowIndex, foreColor);
                changeBackColor(rowIndex, backColor);


                if (lampStatePara.Temperature == 0xfffe) {
                    changeForeColor(rowIndex, 7, Color.Red);
                }
                if (lampStatePara.Current == 0xfffe) {
                    changeForeColor(rowIndex, 8, Color.Red);
                }
                if (lampStatePara.Voltage == 0xfffe) {
                    changeForeColor(rowIndex, 9, Color.Red);
                }
			}
			catch (Exception ex)
			{
				MessageBoxEx.Show(this, ex.Message + ex.StackTrace, tip, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		// 刷新表格中的一行
		private void refreshValues(int rowIndex, int currentSubIndex, int currentPortIndex, LampStatePara lampStatePara, int loopNum, Color foreColor, Color backColor)
		{
			try
			{
				string unSupport = "不支持";
				string overload = "超量程";
				if (LanguageOper.available == true)
				{
					unSupport = LanguageOper.ReadValue(section, "msgStr.1");
					overload = LanguageOper.ReadValue(section, "msgStr.2");
				}

                if (rowIndex > detectDetailGridView.Rows.Count)
                    return;

                //分控号
                detectDetailGridView.Rows[rowIndex].Cells[0].Value = currentSubIndex;
                //端口号
				detectDetailGridView.Rows[rowIndex].Cells[1].Value = currentPortIndex;
                //RDM编号
                detectDetailGridView.Rows[rowIndex].Cells[2].Value = lampStatePara.RdmSeg;

                if (lampStatePara.detect_ok != true) {
                    //for (var i = 3; i < detectDetailGridView.Rows[rowIndex].Cells.Count; i++) {
                    //    detectDetailGridView.Rows[rowIndex].Cells[i].Value = "--";
                    //}
                    detectDetailGridView.Rows[rowIndex].Cells[11].Value = loopNum;
                    changeForeColor(rowIndex, Color.Red);
                    return;
                }

				detectDetailGridView.Rows[rowIndex].Cells[3].Value = lampStatePara.LampIndex;
				detectDetailGridView.Rows[rowIndex].Cells[4].Value = lampStatePara.DmxAddr;
				detectDetailGridView.Rows[rowIndex].Cells[5].Value = lampStatePara.LampChannel;
                detectDetailGridView.Rows[rowIndex].Cells[6].Value = lampStatePara.DebugInfo;
                // 温度
                if (lampStatePara.Temperature == 0xffff) {
                    detectDetailGridView.Rows[rowIndex].Cells[7].Value = unSupport;
                    changeForeColor(rowIndex, 7, Color.Black);
                } else if (lampStatePara.Temperature == 0xfffe) {
                    detectDetailGridView.Rows[rowIndex].Cells[7].Value = overload;
                    changeForeColor(rowIndex, 7, Color.Red);
                } else {
                    detectDetailGridView.Rows[rowIndex].Cells[7].Value = String.Format("{0:f1}", lampStatePara.Temperature / 10.0);
                    changeForeColor(rowIndex, 7, Color.Black);
                }
				// 电流
				if (lampStatePara.Current == 0xffff)
				{
					detectDetailGridView.Rows[rowIndex].Cells[8].Value = unSupport;
					changeForeColor(rowIndex, 8, Color.Black);
				}
				else if (lampStatePara.Current == 0xfffe)
				{
					detectDetailGridView.Rows[rowIndex].Cells[8].Value = overload;
					changeForeColor(rowIndex, 8, Color.Red);
				}
				else
				{
					detectDetailGridView.Rows[rowIndex].Cells[8].Value = String.Format("{0:f3}", lampStatePara.Current / 1000.0);
					changeForeColor(rowIndex, 8, Color.Black);
				}
				// 电压
				if (lampStatePara.Voltage == 0xffff)
				{
					detectDetailGridView.Rows[rowIndex].Cells[9].Value = unSupport;
					changeForeColor(rowIndex, 9, Color.Black);
				}
				else if (lampStatePara.Voltage == 0xfffe)
				{
					detectDetailGridView.Rows[rowIndex].Cells[9].Value = overload;
					changeForeColor(rowIndex, 9, Color.Red);
				}
				else
				{
					detectDetailGridView.Rows[rowIndex].Cells[9].Value = String.Format("{0:f2}", lampStatePara.Voltage / 100.0);
					changeForeColor(rowIndex, 9, Color.Black);
				}
				// 功率 - 电流和电压有一项不支持时，功率也不支持
				if (lampStatePara.Current == 0xffff || lampStatePara.Voltage == 0xffff)
				{
					detectDetailGridView.Rows[rowIndex].Cells[10].Value = unSupport;
				}
				else
				{
					detectDetailGridView.Rows[rowIndex].Cells[10].Value = String.Format("{0:f3}", (lampStatePara.Current / 1000.0) * (lampStatePara.Voltage / 100.0));
				}
				// 周期
                detectDetailGridView.Rows[rowIndex].Cells[11].Value = loopNum;
                // 版本号
                detectDetailGridView.Rows[rowIndex].Cells[12].Value = lampStatePara.Version;

				changeForeColor(rowIndex, foreColor);
				changeBackColor(rowIndex, backColor);
			}
			catch (Exception ex)
			{
				MessageBoxEx.Show(this, ex.Message + ex.StackTrace, tip, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		// 清除表格中的一行
		private void clearValues(int rowIndex)
		{
			try
			{
				if (rowIndex >= 0 && rowIndex < detectDetailGridView.Rows.Count)
				{
					detectDetailGridView.Rows[rowIndex].Cells[0].Value = "";
					detectDetailGridView.Rows[rowIndex].Cells[1].Value = "";
					detectDetailGridView.Rows[rowIndex].Cells[2].Value = "";
					detectDetailGridView.Rows[rowIndex].Cells[3].Value = "";
					detectDetailGridView.Rows[rowIndex].Cells[4].Value = "";
					detectDetailGridView.Rows[rowIndex].Cells[5].Value = "";
					detectDetailGridView.Rows[rowIndex].Cells[6].Value = "";
					detectDetailGridView.Rows[rowIndex].Cells[7].Value = "";
					detectDetailGridView.Rows[rowIndex].Cells[8].Value = "";
					detectDetailGridView.Rows[rowIndex].Cells[9].Value = "";
					detectDetailGridView.Rows[rowIndex].Cells[10].Value = "";
					detectDetailGridView.Rows[rowIndex].Cells[11].Value = "";
					detectDetailGridView.Rows[rowIndex].Cells[12].Value = "";

					changeForeColor(rowIndex, Color.Black);
					changeBackColor(rowIndex, Color.White);
				}
			}
			catch (Exception ex)
			{
				MessageBoxEx.Show(this, ex.Message + ex.StackTrace, tip, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		// 清除表格中的所有行
		private void clearDetectDetailGridView()
		{
			detectDetailGridView.Rows.Clear();
			initTables();
		}

		// 更改行背景色
		private void changeBackColor(int rowIndex, Color backColor)
		{
			if (rowIndex >= 0 && rowIndex < detectDetailGridView.Rows.Count)
			{
				// 保持仅有一行为高亮颜色
				if (backColor == highLightColor)
				{
					detectDetailGridView.Rows[lastHighLightRowIndex].DefaultCellStyle.BackColor = Color.White;
					lastHighLightRowIndex = rowIndex;
				}

				detectDetailGridView.Rows[rowIndex].DefaultCellStyle.BackColor = backColor;
			}
		}

		// 更改行前景色
		private void changeForeColor(int rowIndex, Color foreColor)
		{
            if (rowIndex >= 0 && rowIndex < detectDetailGridView.Rows.Count) {
                //detectDetailGridView.Rows[rowIndex].DefaultCellStyle.ForeColor = foreColor;
                for (var i = 0; i < detectDetailGridView.Rows[rowIndex].Cells.Count; i++) {
                    detectDetailGridView.Rows[rowIndex].Cells[i].Style.ForeColor = foreColor;
                }

            }
		}

		// 改变单元格前景色
		private void changeForeColor(int rowIndex, int cellIndex, Color foreColor)
		{
			if (rowIndex >= 0 && rowIndex < detectDetailGridView.Rows.Count)
			{
				if (cellIndex < detectDetailGridView.Rows[rowIndex].Cells.Count)
				{
					detectDetailGridView.Rows[rowIndex].Cells[cellIndex].Style.ForeColor = foreColor;
				}
			}
		}

		// 更新当前灯具标签
		private void updateCurrentLampLabel(int checkSubIndex, int checkPortIndex, int checkLampIndex)
		{
			string formatStr = "分控 {0} 端口 {1} 灯具 {2}";
			if (LanguageOper.available == true)
			{
				formatStr = LanguageOper.ReadValue(section, "str.3");
			}
			currentLampLabel.Text = String.Format(formatStr, checkSubIndex, checkPortIndex, checkLampIndex);
		}

		// 暂停/继续
		private void pauseButton_Click(object sender, EventArgs e)
		{
			if (pauseFlag == false)
			{
				pauseFlag = true;
				pauseButton.Text = "继 续";
				if (LanguageOper.available == true)
				{
					pauseButton.Text = LanguageOper.ReadValue(section, "pauseButton.Text.0");
				}
			}
			else
			{
				pauseFlag = false;
				pauseButton.Text = "暂 停";
				if (LanguageOper.available == true)
				{
					pauseButton.Text = LanguageOper.ReadValue(section, "pauseButton.Text.1");
				}
			}
		}

		// 开始/停止
		private void startButton_Click(object sender, EventArgs e)
		{
			string startStr = "开 始";
			string pauseStr = "暂 停";
			string stopStr = "停 止";
			if (LanguageOper.available == true)
			{
				startStr = LanguageOper.ReadValue(section, "str.4");
				pauseStr = LanguageOper.ReadValue(section, "str.5");
				stopStr = LanguageOper.ReadValue(section, "str.6");
			}

			// 逻辑动作 - 开始
			if (runningFlag == false)
			{
				if (currentCheckThreadNum > 0)
				{
					return;
				}

				runningFlag = true;
				
				// 尝试重启巡检线程
				restartLampLoopCheck();

				// 重启检测线程失败, 原因为根据布线文件或历史结果, 当前端口没有挂载灯具
				if (runningFlag == false)
				{
					pauseFlag = false;
					needRestart = false;
					lampLoopCheckProcessing = false;
					quickRestartFlag = true;

					startButton.Text = startStr;
					pauseButton.Text = pauseStr;
					pauseButton.Enabled = false;
				}
				// 巡检线程正常启动
				else
				{
					pauseFlag = false;
					startButton.Text = stopStr;
					pauseButton.Text = pauseStr;
					pauseButton.Enabled = true;

					subIndexComboBox.Enabled = false;
					portIndexComboBox.Enabled = false;
					//checkMechodComboBox.Enabled = false;
					checkModeComboBox.Enabled = false;
				}
			}
			// 逻辑动作 - 停止
			else
			{
				pauseFlag = false;
				needRestart = false;
				lampLoopCheckProcessing = false;
				quickRestartFlag = true;

				runningFlag = false;
				startButton.Text = stopStr;
				startButton.Enabled = false;
				pauseButton.Text = pauseStr;
				pauseButton.Enabled = false;

				subIndexComboBox.Enabled = true;
				portIndexComboBox.Enabled = true;
				//checkMechodComboBox.Enabled = true;
                checkModeComboBox.Enabled = true; 

                // 清除灯具巡检标记, 恢复拓扑结构检测
                baseCoreNet.setLampCheckProcessing(false);

                if (activePath == ActivePath.Com) {
                    baseCoreCom.setLampCheckEnable(false);
                }
			}
		}

		// 关闭
		private void okButton_Click(object sender, EventArgs e)
		{
			pauseFlag = false;
			lampLoopCheckProcessing = false;
			
			if (activePath == ActivePath.Com)
			{
				baseCoreCom.setLampCheckEnable(false);
			}
			
			this.DialogResult = System.Windows.Forms.DialogResult.OK;
		}

		// 保存
		private void saveButton_Click(object sender, EventArgs e)
		{
			saveCurrentResults();
		}

		// 使能开始按钮
		private void enableStartButton()
		{
			string startStr = "开 始";
			if (LanguageOper.available == true)
			{
				startStr = LanguageOper.ReadValue(section, "str.4");
			}
			startButton.Text = startStr;
			startButton.Enabled = true;
		}

		// 更改分控检测范围
		private void subIndexComboBox_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (initDone == false)
			{
				return;
			}

			if (subIndexComboBoxAction == false)
			{
				return;
			}

			// 设置要检测的分控
			subIndexPara = subIndexComboBox.SelectedIndex;

			// 重置前台界面
			checkModeComboBox_SelectedIndexChanged(null, null);

			// 快速重启检测过程
			quickRestartFlag = true;
		}

		// 更改端口检测范围
		private void portIndexComboBox_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (initDone == false)
			{
				return;
			}

			// 设置要检测的端口
			portIndexPara = portIndexComboBox.SelectedIndex;

			// 重置前台界面
			checkModeComboBox_SelectedIndexChanged(null, null);

			// 快速重启检测过程
			quickRestartFlag = true;
		}

		// 更改检测模式
		private void checkModeComboBox_SelectedIndexChanged(object sender, EventArgs e)
		{
			// 依据布线文件
			if (checkModeComboBox.SelectedIndex == 0)
			{
				subIndexComboBox.Enabled = true;
				portIndexComboBox.Enabled = true;

				if (referSubTubeDataList == null || referSubTubeDataList.Count == 0)
				{
					string msg = "布线文件中不存在有效灯具点, 将保持当前的检测模式";
					if (LanguageOper.available == true)
					{
						msg = LanguageOper.ReadValue(section, "msgStr.3");
					}
					
					MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
					
					checkModeComboBox.SelectedIndex = lastCheckModeIndex;
					
					return;
				}

				/************************************** 根据布线文件修改当前要检测的分控 ****************************************/
				
				subIndexComboBoxAction = false;

				int currentSelectedSubIndex = subIndexComboBox.SelectedIndex;
				int currentSelectedPortIndex = portIndexComboBox.SelectedIndex;

				string allStr = "全部";
				if (LanguageOper.available == true)
				{
					allStr = LanguageOper.ReadValue(section, "str.0");
				}

				if (currentSelectedSubIndex > referSubTubeDataList.Count)
				{
					string msg = string.Format("布线文件中声明了 {0} 个分控, 当前分控深度（{1}）未在此范围内, 是否从分控 1 开始依据布线文件进行巡检？", referSubTubeDataList.Count, currentSelectedSubIndex);
					if (LanguageOper.available == true)
					{
						msg = string.Format(LanguageOper.ReadValue(section, "msgStr.4"), referSubTubeDataList.Count, currentSelectedSubIndex);
					}
					string tipMsg = msg;
					
					DialogResult dr = MessageBoxEx.Show(this, tipMsg, tip, MessageBoxButtons.YesNo, MessageBoxIcon.Information);
					
					// 从分控 1 开始依据布线文件进行巡检
					if (dr == System.Windows.Forms.DialogResult.Yes)
					{
						subIndexComboBox.Items.Clear();
						subIndexComboBox.Items.Add(allStr);
						for (int i = 1; i <= referSubTubeDataList.Count; i++)
						{
							subIndexComboBox.Items.Add(i);
						}
						subIndexComboBox.SelectedIndex = 1;
						subIndexPara = 1;
					}
					// 恢复之前选择的分控
					else
					{
						checkModeComboBox.SelectedIndex = lastCheckModeIndex;
						subIndexPara = lastCheckModeIndex;
						return;
					}
				}
				else
				{
					subIndexComboBox.Items.Clear();
					subIndexComboBox.Items.Add(allStr);
					for (int i = 1; i <= referSubTubeDataList.Count; i++)
					{
						subIndexComboBox.Items.Add(i);
					}
					subIndexComboBox.SelectedIndex = currentSelectedSubIndex;
				}

				subIndexComboBoxAction = true;

				/************************************** 根据布线文件修改当前要检测的分控 ****************************************/

				// 填充布线文件中声明的灯具
				if (this != null && this.Visible)
				{
					this.Invoke(fillDeclareLampLineDelegate, subIndexPara, portIndexPara);
				}
				else
				{
					return;
				}

				// 检查当前要巡检的灯具数量
				if (detectDetailGridView.Rows.Count == 0 || detectDetailGridView.Rows[0].Cells[0].Value.ToString().Equals(""))
				{
					initTables();
					currentLampLabel.Text = "--";
					effectLampNumLabel.Text = "0";
					checkedLampNumLabel.Text = "0";
				}

				checkMode = LampCheckMode.UseLwf;
				checkAccordingSelectButton.Enabled = false;
				checkAccordingTextBox.Enabled = false;
			}
			// 依据检测结果
			else if (checkModeComboBox.SelectedIndex == 1)
			{
				subIndexComboBox.Enabled = false;
				portIndexComboBox.Enabled = false;

				// 清空当前显示的结果行
				if (this != null && this.Visible)
				{
					this.Invoke(clearDetectDetailGridViewDelegate);
				}
				else
				{
					return;
				}

				// 加载搜索结果中的数据
				if (!checkAccordingTextBox.Text.ToString().Equals(""))
				{
					loadSavedResults(checkAccordingTextBox.Text.ToString());
				}

				checkMode = LampCheckMode.UseResult;
				checkAccordingSelectButton.Enabled = true;
				checkAccordingTextBox.Enabled = true;
			}
			// 实时检测
			else if (checkModeComboBox.SelectedIndex == 2)
			{
				subIndexComboBox.Enabled = true;
				portIndexComboBox.Enabled = true;

                if (detectType==DetectType.ArtNet) {
                    var baseChain = baseCoreNet.GetBaseArtDevChain();
                    if (baseChain == null || baseChain.DetailList.Count == 0) {
                        string msg = "基准设备链不存在, 将保持当前的检测模式";
                        //if (LanguageOper.available == true) {
                        //    msg = LanguageOper.ReadValue(section, "msgStr.3");
                        //}

                        MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);

                        checkModeComboBox.SelectedIndex = lastCheckModeIndex;

                        return;
                    }
                }

				// 清空当前显示的结果行
				if (this != null && this.Visible)
				{
					this.Invoke(clearDetectDetailGridViewDelegate);
				}
				else
				{
					return;
				}

				subIndexComboBoxAction = false;

				int currentSelectedSubIndex = subIndexComboBox.SelectedIndex;

				if (currentSelectedSubIndex > totalSubNum)
				{
					string msg = string.Format("目前选择的分控（{0}）不在系统已检测到的分控范围（1-{1}）内，将自动调整为巡检全部分控", currentSelectedSubIndex, totalSubNum);
					if (LanguageOper.available == true)
					{
						msg = string.Format(LanguageOper.ReadValue(section, "msgStr.5"), currentSelectedSubIndex, totalSubNum);
					}
					
					string tipMsg = msg;
					
					MessageBoxEx.Show(this, tipMsg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
				}

				string allStr = "全部";
				if (LanguageOper.available == true)
				{
					allStr = LanguageOper.ReadValue(section, "str.0");
				}

				subIndexComboBox.Items.Clear();
				subIndexComboBox.Items.Add(allStr);
				for (int i = 1; i <= totalSubNum; i++)
				{
					subIndexComboBox.Items.Add(i.ToString());
				}

				if (currentSelectedSubIndex > totalSubNum)
				{
					subIndexComboBox.SelectedIndex = 0;
				}
				else
				{
					subIndexComboBox.SelectedIndex = currentSelectedSubIndex;
				}

				subIndexComboBoxAction = true;

				checkMode = LampCheckMode.RealTime;
				checkAccordingSelectButton.Enabled = false;
				checkAccordingTextBox.Enabled = false;
			}
			else
			{
				checkModeComboBox.SelectedIndex = lastCheckModeIndex;
				return;
			}

			currentLampLabel.Text = "--";
			effectLampNumLabel.Text = "0";
			checkedLampNumLabel.Text = "0";

			needRestart = true;
			lampLoopCheckProcessing = false;
			quickRestartFlag = true;

			// 记录当前巡检模式
			lastCheckModeIndex = checkModeComboBox.SelectedIndex;
			parentForm.lastLampDetectMode = checkMode;
		}

		// 保存当前结果
		private void saveCurrentResults()
		{
			// 检查当前要保存的结果数量
			if (detectDetailGridView.Rows.Count == 0 || detectDetailGridView.Rows[0].Cells[0].Value.ToString().Equals(""))
			{
				string msg = "当前没有可保存的结果";
				if (LanguageOper.available == true)
				{
					msg = LanguageOper.ReadValue(section, "msgStr.6");
				}
				
				MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
				
				return;
			}

			try
			{
				if (checkLoopNum < 2)
				{
					string msg = "尚未完成一次完整搜索, 请等待";
					if (LanguageOper.available == true)
					{
						msg = LanguageOper.ReadValue(section, "msgStr.7");
					}
					
					MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
					
					return;
				}

				bool tempPauseFlag = false;
				
				if (runningFlag == true && pauseFlag == false)
				{
					pauseButton.PerformClick();
					tempPauseFlag = true;
				}

				// 收集界面上显示的结果
				List<LampStatePara> lampStateParaList = new List<LampStatePara>();
				for (int rowIndex = 0; rowIndex < detectDetailGridView.Rows.Count; rowIndex++)
				{
					DataGridViewRow currentRow = detectDetailGridView.Rows[rowIndex];

					if (currentRow.Cells[0].Value.ToString().Equals(""))
					{
						continue;
					}

					LampStatePara oneLampState = new LampStatePara();
					oneLampState.SubIndex = int.Parse(currentRow.Cells[0].Value.ToString());
					oneLampState.PortIndex = int.Parse(currentRow.Cells[1].Value.ToString());
					oneLampState.LampIndex = int.Parse(currentRow.Cells[2].Value.ToString());
					// DMX地址
					if (currentRow.Cells[3].Value == null || currentRow.Cells[3].Value.ToString().Equals("--"))
					{
						oneLampState.DmxAddr = -1;
					}
					else
					{
						oneLampState.DmxAddr = int.Parse(currentRow.Cells[3].Value.ToString());
					}
					// 灯具类型 - 暂无
					// 灯具ID
					if (currentRow.Cells[5].Value == null || currentRow.Cells[5].Value.ToString().Equals("--"))
					{
						oneLampState.LampId = -1;
					}
					else
					{
						oneLampState.LampId = int.Parse(currentRow.Cells[5].Value.ToString());
					}
					// 电流
					if (currentRow.Cells[6].Value == null || currentRow.Cells[6].Value.ToString().Equals("--"))
					{
						oneLampState.Current = int.MinValue;
					}
					else
					{
						oneLampState.Current = (int)(double.Parse(currentRow.Cells[6].Value.ToString()) * 1000);
					}
					// 电压
					if (currentRow.Cells[7].Value == null || currentRow.Cells[7].Value.ToString().Equals("--"))
					{
						oneLampState.Voltage = int.MinValue;
					}
					else
					{
						oneLampState.Voltage = (int)(double.Parse(currentRow.Cells[7].Value.ToString()) * 100);
					}
					// 温度
					if (currentRow.Cells[8].Value == null || currentRow.Cells[8].Value.ToString().Equals("--"))
					{
						oneLampState.Temperature = int.MinValue;
					}
					else
					{
						oneLampState.Temperature = (int)(double.Parse(currentRow.Cells[8].Value.ToString()) * 10);
					}
					// 功率		- 计算值
					// 巡检周期	- 动态值

					lampStateParaList.Add(oneLampState);
				}

				SaveFileDialog s = new SaveFileDialog();
				s.Filter = "Json Files(*.json)|*.json";
				s.FileName = "LampDetectResult.json";
				s.FilterIndex = 1;
				if (s.ShowDialog() == DialogResult.OK)
				{
					string jsonStr = JsonConvert.SerializeObject(lampStateParaList, Formatting.Indented);
					using (StreamWriter writer = new StreamWriter(s.FileName))
					{
						writer.WriteLine(jsonStr);
						writer.Flush();
					}
					string msg = "结果文件保存成功";
					if (LanguageOper.available == true)
					{
						msg = LanguageOper.ReadValue(section, "msgStr.8");
					}
					MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
				}

				if (tempPauseFlag == true)
				{
					pauseButton.PerformClick();
				}
			}
			catch (Exception ex)
			{
				MessageBoxEx.Show(this, ex.Message + ex.StackTrace, tip, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		// 选择保存的 Json 结果
		private void checkAccordingSelectButton_Click(object sender, EventArgs e)
		{
			OpenFileDialog o = new OpenFileDialog();
			o.Filter = "Json Files(*.json)|*.json";
			o.Multiselect = false;
			if (Directory.Exists(lastPath_CheckAccordingFile))
			{
				o.InitialDirectory = lastPath_CheckAccordingFile;
			}
			else
			{
				o.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
			}
			DialogResult dr = o.ShowDialog();
			if (dr == DialogResult.OK)
			{
				bool res = loadSavedResults(o.FileName);
				if (res == true)
				{
					lastPath_CheckAccordingFile = (new FileInfo(o.FileName)).DirectoryName;
					checkAccordingTextBox.Text = o.FileName;
					checkAccordingTextBox.SelectionStart = checkAccordingTextBox.Text.Length;
					checkAccordingTextBox.ScrollToCaret();
					parentForm.lastCheckAccordingFilePath = o.FileName;
				}
				else
				{
					checkAccordingTextBox.Text = "";
					parentForm.lastCheckAccordingFilePath = "";
				}
			}
		}

		// 加载搜索结果中的数据
		private bool loadSavedResults(string jsonFilePath)
		{
			try
			{
				if (!File.Exists(jsonFilePath))
				{
					string msg = string.Format("文件 {0} 不存在", jsonFilePath);
					if (LanguageOper.available == true)
					{
						msg = string.Format(LanguageOper.ReadValue(section, "msgStr.1"), jsonFilePath);
					}
					
					MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
					
					referResultLampList = null;
					
					return false;
				}

				using(StreamReader reader = new StreamReader(jsonFilePath))
				{
					StringBuilder sb = new StringBuilder();
					while (true)
					{
						string line = reader.ReadLine();
						if (line == null)
						{
							break;
						}
						else
						{
							sb.Append(line);
						}
					}

					referResultLampList = JsonConvert.DeserializeObject<List<LampStatePara>>(sb.ToString());

					this.Invoke(fillReferResultLampLineDelegate);
				}

				return true;
			}
			catch (Exception)
			{
				string msg = string.Format("文件 {0} 解析错误, 请检查文件内容", jsonFilePath);
				if (LanguageOper.available == true)
				{
					msg = string.Format(LanguageOper.ReadValue(section, "msgStr.9"), jsonFilePath);
				}
				
				MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
				
				referResultLampList = null;
				
				return false;
			}
		}

		// 保存检测模式
		private void saveCheckModeCheckBox_CheckedChanged(object sender, EventArgs e)
		{
			if (initDone == false)
			{
				return;
			}

			if (saveCheckModeCheckBox.Checked)
			{
                if (checkModeComboBox.SelectedIndex == 0) {
                    parentForm.lastLampDetectMode = LampCheckMode.UseLwf;
                } else if (checkModeComboBox.SelectedIndex == 1) {
                    parentForm.lastLampDetectMode = LampCheckMode.UseResult;
                } else if (checkModeComboBox.SelectedIndex == 2) {
                    parentForm.lastLampDetectMode = LampCheckMode.RealTime;
                }
			}
			else
			{
				parentForm.lastLampDetectMode = LampCheckMode.RealTime;
			}

			parentForm.saveLampCheckModeChecked = saveCheckModeCheckBox.Checked;
		}

		// 查看电流、电压、温度、功率
		private void showCVTPCheckBox_CheckedChanged(object sender, EventArgs e)
		{
			detectDetailGridView.Columns[6].Visible = showCVTPCheckBox.Checked;
			detectDetailGridView.Columns[7].Visible = showCVTPCheckBox.Checked;
			detectDetailGridView.Columns[8].Visible = showCVTPCheckBox.Checked;
			detectDetailGridView.Columns[9].Visible = showCVTPCheckBox.Checked;
		}

		// 查看版本号、RDM编号
		private void showVRCheckBox_CheckedChanged(object sender, EventArgs e)
		{
			detectDetailGridView.Columns[10].Visible = showVRCheckBox.Checked;
			detectDetailGridView.Columns[11].Visible = showVRCheckBox.Checked;
		}

		// 查看调试信息
		private void showDebugCheckBox_CheckedChanged(object sender, EventArgs e)
		{
			detectDetailGridView.Columns[5].Visible = showDebugCheckBox.Checked;
		}
	}

	// 双缓冲解决闪烁
	public class DoubleBufferDataGridView : DataGridView
	{
		public DoubleBufferDataGridView()
		{
			SetStyle(ControlStyles.DoubleBuffer | ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
			UpdateStyles();
		}
	}

	public enum LampCheckMethod
	{
		CheckState = 0,
		CheckLink = 1
	}

	public enum LampCheckMode
	{
		UseLwf = 0,
		UseResult = 1,
		RealTime = 2
	}
}
